views:

91

answers:

2

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 namespace, 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?

+2  A: 

Have a look at:

Custom events in jQuery open doors to complex behaviors

jQuery Custom Events: They Will Rock Your World!

Sarfraz
Thanks, will definitely read up on that!
AnC
+3  A: 

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" });
J-P
I had not realized you could/should wrap jQuery around a regular object - but this works great, and might even mean I don't need to namespace the event name (as binding the event to a particular object already prevents clashes). Thanks!
AnC
One thing to remember will be that while we can bind events to any JavaScript object, we cannot remove them with `unbind`. Need to use `removeData` for that.
Anurag
I did not know that! Will need to find a good resource for reading up on it...
AnC