Embed URL

HTTPS clone URL

SSH clone URL

Four Ways To Do Pub/Sub With jQuery 1.7 and jQuery UI (in the future)

Between jQuery 1.7 and some of work going into future versions of jQuery UI, there are a ton of hot new ways for you to get your publish/subscribe on. Here are just four of them, three of which are new.

Option 1: Using jQuery 1.7's $.Callbacks() feature:

$.Callbacks are a multi-purpose callbacks list object which can be used as a base layer to build new functionality including simple publish/subscribe systems. We haven't yet released the API documentation for this feature just yet, but for more information on it (including lots of examples), see my post on $.Callbacks() here:
http://addyosmani.com/blog/jquery-1-7s-callbacks-feature-demystified/.

Option 2: Custom events using .on() and .off():

In jQuery 1.7, we updated the events API to support two new methods: .on() and .off(). These methods are meant to simplify the usage of .bind(),.live() and .delegate() such that rather than relying on developers to know which of these options is the best to use, all developers can simply use .on() and .off() and we'll make the best logic decisions for what to use beneath the hood. Note: As of jQuery 1.7 all of these three methods (bind/live/delegate) use .on() and .off() when you call them, so calling these newer methods directly is advised.

Option 3: Using jQuery UI $.Observable

Note: $.Observables are currently still evolving and will not be available in jQuery UI until the jQueryUI Grid itself is released (http://wiki.jqueryui.com/w/page/34246941/Grid). The below is provided as a preview of what's being developed. Feel free to play around with the demos and submit any feedback or comments you may have about it.

The basic idea behind observables are that when objects/collections of data are changed or updated, events often need to be triggered to inform any observers of the change. This is a concept you see in a few different
frameworks (Backbone's Collections for example). I believe the idea with this is that jQuery UI intend on applying this concept to UI components in particular (which should be very interesting to see).

There are of course many, many library agnostic Pub/Sub implementations that have been written
(Shameless plug: I've also done one https://github.com/addyosmani/pubsubz/), but this rough guide
will be focusing on jQuery for the most part. Here's Peter's implementation and a demo: