简体   繁体   中英

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) {
...
});

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 .

I think that using jQuery's callbacks ($.Callbacks()) makes for much cleaner code and is much more organized than your method of binding a function to a window. You have more flexibility because you don't have to know the name(s) of the event(s) to be used when firing the callback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM