Web App Development

jQuery.Callbacks objects

The jQuery.Callbacks object provides functionality for callback lists: Callbacks can be collected and fired collectively when necessary.

Initially I thought that callback lists would help when waiting for multiple callbacks to be called, for example when waiting for multiple Ajax responses. That's not the case, you can use jQuery deferred objects for that.

Creating a callback list, adding a callback and triggering the list callbacks

The necessary functions for this are $.Callbacks, .add and fire:
var handler = function(){
console.log("Handling whatever caused the callback list to fire");
};
var cb = $.Callbacks();
cb.add(handler);
cb.fire(); // Logs "Handling whatever caused the callback list to fire"
You can add multiple callbacks to the list, if you add the same one twice it will be called twice. Use `remove` to delete a handler and `empty` to remove all handlers.

A playground for exploring other functions of callback objects

I made a playground that let's you explore $.Callbacks' behavior and additional functions. I'll describe some of them below.

Functions of callback lists

fireWith(execution context, arguments)
Invoke callbacks in the list with the given arguments and execution context ("this").

lock
Prevent changes to the callback list.

disable
Remove all callbacks and lock the callback list (i.e. prevent adding new handlers).

has(callback)
Returns a boolean indicating whether the given callback has been added to the callback list.

Passing flags to the callback list

You can pass flags to the callback list constructor to modify its behavior. The following flags are available:

memory
Remember arguments of last invocation and call any newly added callback with these arguments.

once
Only allow calling fire once.

unique
Ignore duplicates added with add.

stopOnFalse
As soon as one callback returns false stop going through the list of callbacks.

Comments

chandra
good one.

Follow me on Twitter