jQuery Callback and Pub / Sub
Asked Answered
T

2

7

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) {
...
});
Thyrsus answered 17/12, 2012 at 19:46 Comment(2)
I'm guessing you need to expand a little on your question! What callbacks, and how do you intend to use them. What are you using those custom events for specifically etc. A pub / sub system can be a lot of different things.Yost
Fair comment - I have added some more infoThyrsus
C
1

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.

Caenogenesis answered 17/12, 2012 at 20:2 Comment(0)
C
1

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.

Cacus answered 17/12, 2012 at 20:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.