jQuery.Callbacks()


jQuery.Callbacks( flags )Returns: Callbacks

Description: A multi-purpose callbacks list object that provides a powerful way to manage callback lists.

The $.Callbacks() function is internally used to provide the base functionality behind the jQuery $.ajax() and $.Deferred() components. It can be used as a similar base to define functionality for new components.

$.Callbacks() supports a number of methods including callbacks.add(),callbacks.remove(), callbacks.fire() and callbacks.disable().

Getting started

The following are two sample methods named fn1 and fn2:

1
2
3
4
5
6
7
8
function fn1( value ) {
console.log( value );
}
function fn2( value ) {
console.log( "fn2 says: " + value );
return false;
}

These can be added as callbacks to a $.Callbacks list and invoked as follows:

1
2
3
4
5
6
7
8
9
10
var callbacks = $.Callbacks();
callbacks.add( fn1 );
// Outputs: foo!
callbacks.fire( "foo!" );
callbacks.add( fn2 );
// Outputs: bar!, fn2 says: bar!
callbacks.fire( "bar!" );

The result of this is that it becomes simple to construct complex lists of callbacks where input values can be passed through to as many functions as needed with ease.

Two specific methods were being used above: .add() and .fire(). The .add() method supports adding new callbacks to the callback list, while the .fire() method executes the added functions and provides a way to pass arguments to be processed by the callbacks in the same list.

Another method supported by $.Callbacks is .remove(), which has the ability to remove a particular callback from the callback list. Here's a practical example of .remove() being used:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var callbacks = $.Callbacks();
callbacks.add( fn1 );
// Outputs: foo!
callbacks.fire( "foo!" );
callbacks.add( fn2 );
// Outputs: bar!, fn2 says: bar!
callbacks.fire( "bar!" );
callbacks.remove( fn2 );
// Only outputs foobar, as fn2 has been removed.
callbacks.fire( "foobar" );

Supported Flags

The flags argument is an optional argument to $.Callbacks(), structured as a list of space-separated strings that change how the callback list behaves (eg. $.Callbacks( "unique stopOnFalse" )).

Possible flags:

  • once: Ensures the callback list can only be fired once (like a Deferred).
  • memory: Keeps track of previous values and will call any callback added after the list has been fired right away with the latest "memorized" values (like a Deferred).
  • unique: Ensures a callback can only be added once (so there are no duplicates in the list).
  • stopOnFalse: Interrupts callings when a callback returns false.

By default a callback list will act like an event callback list and can be "fired" multiple times.

For examples of how flags should ideally be used, see below:

$.Callbacks( "once" ):

1
2
3
4
5
6
7
8
9
10
11
12
var callbacks = $.Callbacks( "once" );
callbacks.add( fn1 );
callbacks.fire( "foo" );
callbacks.add( fn2 );
callbacks.fire( "bar" );
callbacks.remove( fn2 );
callbacks.fire( "foobar" );
/*
output:
foo
*/

$.Callbacks( "memory" ):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var callbacks = $.Callbacks( "memory" );
callbacks.add( fn1 );
callbacks.fire( "foo" );
callbacks.add( fn2 );
callbacks.fire( "bar" );
callbacks.remove( fn2 );
callbacks.fire( "foobar" );
/*
output:
foo
fn2 says:foo
bar
fn2 says:bar
foobar
*/

$.Callbacks( "unique" ):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var callbacks = $.Callbacks( "unique" );
callbacks.add( fn1 );
callbacks.fire( "foo" );
callbacks.add( fn1 ); // Repeat addition
callbacks.add( fn2 );
callbacks.fire( "bar" );
callbacks.remove( fn2 );
callbacks.fire( "foobar" );
/*
output:
foo
bar
fn2 says:bar
foobar
*/

$.Callbacks( "stopOnFalse" ):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function fn1( value ) {
console.log( value );
return false;
}
function fn2( value ) {
fn1( "fn2 says: " + value );
return false;
}
var callbacks = $.Callbacks( "stopOnFalse" );
callbacks.add( fn1 );
callbacks.fire( "foo" );
callbacks.add( fn2 );
callbacks.fire( "bar" );
callbacks.remove( fn2 );
callbacks.fire( "foobar" );
/*
output:
foo
bar
foobar
*/

Because $.Callbacks() supports a list of flags rather than just one, setting several flags has a cumulative effect similar to "&&". This means it's possible to combine flags to create callback lists that, say, both are unique and ensure if list was already fired, adding more callbacks will have it called with the latest fired value (i.e. $.Callbacks("unique memory")).

$.Callbacks( 'unique memory' ):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function fn1( value ) {
console.log( value );
return false;
}
function fn2( value ) {
fn1( "fn2 says: " + value );
return false;
}
var callbacks = $.Callbacks( "unique memory" );
callbacks.add( fn1 );
callbacks.fire( "foo" );
callbacks.add( fn1 ); // Repeat addition
callbacks.add( fn2 );
callbacks.fire( "bar" );
callbacks.add( fn2 );
callbacks.fire( "baz" );
callbacks.remove( fn2 );
callbacks.fire( "foobar" );
/*
output:
foo
fn2 says:foo
bar
fn2 says:bar
baz
fn2 says:baz
foobar
*/

Flag combinations with $.Callbacks() are internally in jQuery for the .done() and .fail() functions on a Deferred — both of which use $.Callbacks('memory once').

The methods of $.Callbacks can also be detached, should there be a need to define short-hand versions for convenience:

1
2
3
4
5
6
7
8
var callbacks = $.Callbacks(),
add = callbacks.add,
remove = callbacks.remove,
fire = callbacks.fire;
add( fn1 );
fire( "hello world" );
remove( fn1 );

$.Callbacks, $.Deferred and Pub/Sub

The general idea behind pub/sub (Publish/Subscribe, or, the Observer pattern) is the promotion of loose coupling in applications. Rather than single objects calling on the methods of other objects, an object instead subscribes to a specific task or activity of another object and is notified when it occurs. Observers are also called Subscribers, and we refer to the object being observed as the Publisher (or the subject). Publishers notify subscribers when events occur.

To demonstrate the component-creation capabilities of $.Callbacks(), it's possible to implement a Pub/Sub system using only callback lists. Using $.Callbacks as a topics queue, a system for publishing and subscribing to topics can be implemented as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var topics = {};
jQuery.Topic = function( id ) {
var callbacks, method,
topic = id && topics[ id ];
if ( !topic ) {
callbacks = jQuery.Callbacks();
topic = {
publish: callbacks.fire,
subscribe: callbacks.add,
unsubscribe: callbacks.remove
};
if ( id ) {
topics[ id ] = topic;
}
}
return topic;
};

This can then be used by parts of your application to publish and subscribe to events of interest quite easily:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Subscribers
$.Topic( "mailArrived" ).subscribe( fn1 );
$.Topic( "mailArrived" ).subscribe( fn2 );
$.Topic( "mailSent" ).subscribe( fn1 );
// Publisher
$.Topic( "mailArrived" ).publish( "hello world!" );
$.Topic( "mailSent" ).publish( "woo! mail!" );
// Here, "hello world!" gets pushed to fn1 and fn2
// when the "mailArrived" notification is published
// with "woo! mail!" also being pushed to fn1 when
// the "mailSent" notification is published.
/*
output:
hello world!
fn2 says: hello world!
woo! mail!
*/

While this is useful, the implementation can be taken further. Using $.Deferreds, it's possible to ensure publishers only publish notifications for subscribers once particular tasks have been completed (resolved). See the below code sample for some further comments on how this could be used in practice:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Subscribe to the mailArrived notification
$.Topic( "mailArrived" ).subscribe( fn1 );
// Create a new instance of Deferreds
var dfd = $.Deferred();
// Define a new topic (without directly publishing)
var topic = $.Topic( "mailArrived" );
// When the deferred has been resolved, publish a
// notification to subscribers
dfd.done( topic.publish );
// Here the Deferred is being resolved with a message
// that will be passed back to subscribers. It's possible to
// easily integrate this into a more complex routine
// (eg. waiting on an Ajax call to complete) so that
// messages are only published once the task has actually
// finished.
dfd.resolve( "it's been published!" );