In the past I have done very simple pub / sub in jQuery by binding on the window.
// subscribe
$( window ).on("someEvent", function() { ... });
// publish
$( window ).trigger("someEvent");
However I recently learned about the new callbacks feature, which seems to be the recommended way of handling pub / sub in jQuery.
What are the advantages of using callback, as opposed to just binding on the window? For a simple system like the one above, is using the Callback feature overkill?
Edit: Here is a bit more info about how I commonly use the above...
This is something that I will sometimes do to allow my jQuery plugins to talk to each other. For example, I have my own draggable and droppable plugins that need to communicate.
When dragging starts, updates and stops, the draggable plugin triggers custom events on the window. The droppable plugin watches these events and reacts accordingly.
// in draggable
onStart: function() {
$( window ).trigger("dragger.start", [data]);
}
// in droppable
$( window ).on("dragger.start", function(event, data) {
...
});
Binding to the window is not problematic in and of itself, but because other events can be bound to and unbound from the window your system can have side effects that you do not intend. For example, $(window).off()
will unbind "someEvent"
even if it was only your intention to unbind more common events like "scroll"
or "click"
.
I wouldn't say that using Callbacks is overkill because it's relatively simple -- I would say even simpler than what you've done:
var callbacks = $.Callbacks();
callbacks.add(function () { ... });
callbacks.fire();
That is all you would need to replace your sample code. One advantage I see immediately is that you don't need to know the name of the event you need to trigger during the trigger phase; it's handled more transparently, which is often nice.
You can also add multiple function calls to a single callback or have multiple callbacks simultaneously. This is harder to do if you're just using window
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With