开发者

global custom events in jQuery

开发者 https://www.devze.com 2023-01-08 09:15 出处:网络
I want to use custom jQuery events independent of DOM elements, but I\'m not sure what the best way is to achieve this.

I want to use custom jQuery events independent of DOM elements, but I'm not sure what the best way is to achieve this.

Here's what I started out with:

// some system component registers an event handler
$().bind("foo.bar", handler); // foo is my app's nam开发者_StackOverflowespace, bar is event name
// another part of the system fires off the event
$().trigger("foo.bar", { context: "lorem ipsum" });

After looking at jQuery's source, in particular its handling of global AJAX events, I figured this should work:

$.fn.bind("foo.bar", handler);
// ...
$.event.trigger("foo.bar", { context: "lorem ipsum" });

However, it appears that my handler function is never even called.

Am I perhaps going about this the wrong way?


If you're using jQuery >1.4 then $() returns an empty jQuery collection which would mean that no event handler is actually bound to anything. Before 1.4 it would have returned the same as jQuery(document).

It might be better to simply have a global namespace (an actual object) and then add events to that:

var FOO = {};

$(FOO).bind("foo.bar", handler);

$(FOO).trigger("foo.bar", { context: "lorem ipsum" });


I found my way here because I was looking to implement the publisher/subscriber pattern using namespaced custom events using jQuery. While the accepted solution is a way to use $.event.trigger() in a way that is not tied to DOM elements, it won't work well for a true global event implementation in a publisher/subscriber architecture (such as with a complex UI with many asynchronous actions), where you want to have arbitrary objects/elements listen for a custom event.

Through experimentation, I've found that the real answer to why AnC's events were not firing is because jQuery apparently doesn't allow the "." (period) character in custom event names...but underscores seem to be ok.

So, if you name your events something like foo_bar (rather than foo.bar), your code should work as expected. Tested with jQuery 1.4.4.

Edit: Just to be clear - I mean that periods aren't allowed for custom events if you want to use the $.event.trigger() mechanism. In scenarios where events are being triggered by objects or elements, periods seem to be ok...not sure if this is a bug or by design.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号