{"name":"jQuery.Callbacks","type":"method","title":"jQuery.Callbacks()","deprecated":null,"removed":null,"desc":"A multi-purpose callbacks list object that provides a powerful way to manage callback lists.","categories":["callbacks-object","version/1.7"],"entries":[{"return":"Callbacks","signatures":{"added":"1.7","argument":{"desc":"An optional list of space-separated flags that change how the callback list behaves.","name":"flags","type":"String"}},"examples":null,"longdesc":"\n

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.

\n

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

\n

Getting started

\n

The following are two sample methods named fn1 and fn2:

\n
\nfunction fn1( value ) {\n  console.log( value );\n}\n\nfunction fn2( value ) {\n  console.log( \"fn2 says: \" + value );\n  return false;\n}\n    
\n

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

\n
\nvar callbacks = $.Callbacks();\ncallbacks.add( fn1 );\n\n// Outputs: foo!\ncallbacks.fire( \"foo!\" );\n\ncallbacks.add( fn2 );\n\n// Outputs: bar!, fn2 says: bar!\ncallbacks.fire( \"bar!\" );\n    
\n

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.

\n

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.

\n

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:

\n
\nvar callbacks = $.Callbacks();\ncallbacks.add( fn1 );\n\n// Outputs: foo!\ncallbacks.fire( \"foo!\" );\n\ncallbacks.add( fn2 );\n\n// Outputs: bar!, fn2 says: bar!\ncallbacks.fire( \"bar!\" );\n\ncallbacks.remove( fn2 );\n\n// Only outputs foobar, as fn2 has been removed.\ncallbacks.fire( \"foobar\" );\n    
\n

Supported Flags

\n

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\" )).

\n

Possible flags:

\n \n

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

\n

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

\n

$.Callbacks( \"once\" ):

\n
\nvar callbacks = $.Callbacks( \"once\" );\ncallbacks.add( fn1 );\ncallbacks.fire( \"foo\" );\ncallbacks.add( fn2 );\ncallbacks.fire( \"bar\" );\ncallbacks.remove( fn2 );\ncallbacks.fire( \"foobar\" );\n\n/*\noutput:\nfoo\n*/\n    
\n

$.Callbacks( \"memory\" ):

\n
\nvar callbacks = $.Callbacks( \"memory\" );\ncallbacks.add( fn1 );\ncallbacks.fire( \"foo\" );\ncallbacks.add( fn2 );\ncallbacks.fire( \"bar\" );\ncallbacks.remove( fn2 );\ncallbacks.fire( \"foobar\" );\n\n/*\noutput:\nfoo\nfn2 says:foo\nbar\nfn2 says:bar\nfoobar\n*/\n    
\n

$.Callbacks( \"unique\" ):

\n
\nvar callbacks = $.Callbacks( \"unique\" );\ncallbacks.add( fn1 );\ncallbacks.fire( \"foo\" );\ncallbacks.add( fn1 ); // Repeat addition\ncallbacks.add( fn2 );\ncallbacks.fire( \"bar\" );\ncallbacks.remove( fn2 );\ncallbacks.fire( \"foobar\" );\n\n/*\noutput:\nfoo\nbar\nfn2 says:bar\nfoobar\n*/\n    
\n

$.Callbacks( \"stopOnFalse\" ):

\n
\nfunction fn1( value ) {\n  console.log( value );\n  return false;\n}\n\nfunction fn2( value ) {\n  fn1( \"fn2 says: \" + value );\n  return false;\n}\n\nvar callbacks = $.Callbacks( \"stopOnFalse\" );\ncallbacks.add( fn1 );\ncallbacks.fire( \"foo\" );\ncallbacks.add( fn2 );\ncallbacks.fire( \"bar\" );\ncallbacks.remove( fn2 );\ncallbacks.fire( \"foobar\" );\n\n/*\noutput:\nfoo\nbar\nfoobar\n*/\n    
\n

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\")).

\n

$.Callbacks( 'unique memory' ):

\n
\nfunction fn1( value ) {\n  console.log( value );\n  return false;\n}\n\nfunction fn2( value ) {\n  fn1( \"fn2 says: \" + value );\n  return false;\n}\n\nvar callbacks = $.Callbacks( \"unique memory\" );\ncallbacks.add( fn1 );\ncallbacks.fire( \"foo\" );\ncallbacks.add( fn1 ); // Repeat addition\ncallbacks.add( fn2 );\ncallbacks.fire( \"bar\" );\ncallbacks.add( fn2 );\ncallbacks.fire( \"baz\" );\ncallbacks.remove( fn2 );\ncallbacks.fire( \"foobar\" );\n\n/*\noutput:\nfoo\nfn2 says:foo\nbar\nfn2 says:bar\nbaz\nfn2 says:baz\nfoobar\n*/\n
\n

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

\n

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

\n
\nvar callbacks = $.Callbacks(),\n  add = callbacks.add,\n  remove = callbacks.remove,\n  fire = callbacks.fire;\n\nadd( fn1 );\nfire( \"hello world\" );\nremove( fn1 );\n    
\n

$.Callbacks, $.Deferred and Pub/Sub

\n

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.

\n

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:

\n
\nvar topics = {};\n\njQuery.Topic = function( id ) {\n  var callbacks, method,\n    topic = id && topics[ id ];\n\n  if ( !topic ) {\n    callbacks = jQuery.Callbacks();\n    topic = {\n      publish: callbacks.fire,\n      subscribe: callbacks.add,\n      unsubscribe: callbacks.remove\n    };\n    if ( id ) {\n      topics[ id ] = topic;\n    }\n  }\n  return topic;\n};\n    
\n

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

\n
\n// Subscribers\n$.Topic( \"mailArrived\" ).subscribe( fn1 );\n$.Topic( \"mailArrived\" ).subscribe( fn2 );\n$.Topic( \"mailSent\" ).subscribe( fn1 );\n\n// Publisher\n$.Topic( \"mailArrived\" ).publish( \"hello world!\" );\n$.Topic( \"mailSent\" ).publish( \"woo! mail!\" );\n\n// Here, \"hello world!\" gets pushed to fn1 and fn2\n// when the \"mailArrived\" notification is published\n// with \"woo! mail!\" also being pushed to fn1 when\n// the \"mailSent\" notification is published.\n\n/*\noutput:\nhello world!\nfn2 says: hello world!\nwoo! mail!\n*/\n    
\n

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:

\n
\n// Subscribe to the mailArrived notification\n$.Topic( \"mailArrived\" ).subscribe( fn1 );\n\n// Create a new instance of Deferreds\nvar dfd = $.Deferred();\n\n// Define a new topic (without directly publishing)\nvar topic = $.Topic( \"mailArrived\" );\n\n// When the deferred has been resolved, publish a\n// notification to subscribers\ndfd.done( topic.publish );\n\n// Here the Deferred is being resolved with a message\n// that will be passed back to subscribers. It's possible to\n// easily integrate this into a more complex routine\n// (eg. waiting on an ajax call to complete) so that\n// messages are only published once the task has actually\n// finished.\ndfd.resolve( \"it's been published!\" );\n    
\n "}]}