Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Callback and Pub / Sub

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) {
...
});
like image 568
user1031947 Avatar asked Dec 17 '12 19:12

user1031947


1 Answers

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.

like image 93
Explosion Pills Avatar answered Oct 21 '22 18:10

Explosion Pills