Decoding jQuery – Callbacks Object

In the Decoding jQuery series, we will break down every single method in jQuery, to study the beauty of the framework, as an appreciation to the collective/creative geniuses behind it.

The jQuery.Callbacks() function, introduced in version 1.7, returns a multi-purpose object that provides a powerful way to manage callback lists. It supports adding, removing, firing, and disabling callbacks. (jQuery API Doc)

It provides many Supported Flags. It is structured as a list of space-separated strings that change how the callback list behaves (eg. $.Callbacks( ‘unique stopOnFalse’ )).

Callbacks Object can also be used to do pub/sub and it is also used to make jQuery.Deferred().

1. Structure of jQuery.Callbacks()

Below is how the structure of jQuery.Callbacks() function looks like in jQuery source(callbacks.js).

jQuery.Callbacks = function( flags ) {

  // Convert flags from String-formatted to Object-formatted
  // (we check in cache first)
  flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {};

  var // Actual callback list
    list = [],
    // Stack of fire calls for repeatable lists
    stack = [],
    // Add one or several callbacks to the list
    add = function( args ) {
    // Fire callbacks
    fire = function( context, args ) {
    self = {

  return self;

add function – adds a list of callbacks to the variable list array.

fire function – loops through the items in the list and fire them one by one.

self object – is the actual Callbacks object returned at the end of the function.

The most important methods in the self object are:
add() adds a callback or a collection of callbacks to the list, this is the one we use to build subscribe in pub/sub function
fireWith() method actually calls all callbacks with the given context and arguments
fire() method inside the self object executes fireWith with the object as the context, this is the one we use to build publish in pub/sub function

There are also many other essential and useful methods in the self object, they are:
has(): a boolean check to find out if a callback list contains a specific callback
remove(): Remove a callback from the list
empty(): a method for emptiying a callback list of all callbacks added so far
disable(): disables further calls being made to the callback list
lock(): lock the list in its current state

2. How to use Callbacks object
Suppose we have a Rails application, assume we have a function displayAlert and msgStatus like the ones below.

var displayAlert = function( msg ) {
      console.log( msg );
    msgStatus = function ( msg ) {
      fn1(msg + '...feed is read!');
      return false;
    callbacks = $.Callbacks();
callbacks.add( displayAlert ); 'new message 1' ); // outputs: new message 1
callbacks.add( msgStatus ); 'new message 2' ); // outputs: new message 2, new message 2 is read!

After creating a callbacks = $.Callbacks();, we can use add to add displayAlert to the callbacks variable as a list item, and later add postFeed as a new item. By using fire, the callbacks object is fired with the function/functions executed.

As explained above, fire is actually fireWith with the object itself as the context, you can also define/specify a context and arguments for callbacks being bound and fired.

var fn = function (argA, argB) {
callbacks.add( fn );
callbacks.fireWith( window, ['foo', 'bar']);
// outputs: foo, bar

Addy Osmani provided example code for some of these methods and some of the flags arguments in his Demystifying jQuery 1.7’s $.Callbacks

3. How does a pub/sub function work

Below is an example of building a jQuery.Actions for publish and subscribe when microposts are received/sent, as well as sent status.

var displayAlert = function(msg) {

var msgStatus = function(msg) {
var actionItems = {};

jQuery.Actions = function( id ) {
  var callbacks,
      action = id && actionItems[ id ];
  if ( !action ) {
    callbacks = jQuery.Callbacks();
    action = {
      subscribe: callbacks.add,
      unsubscribe: callbacks.remove
    if ( id ) {
      actionItems[ id ] = action;
  return action;

// Subscribers

// Publisher
$.Actions('micropostArrived').publish('New Items arrived');
$.Actions('micropostSent').publish('Item posted');

In the above example, the publish and subscribe use fire and add for the pub/sub pattern, and remove for unsubscribe.

This is not the only way to use jQuery for pub/sub, Addy’s Four Ways To Do Pub/Sub With jQuery 1.7 and jQuery UI gist discussed more ways of doing it with jQuery and jQuery UI.

Be Sociable, Share!

About Shi Chuan

I am a web developer.
This entry was posted in JavaScript and tagged . Bookmark the permalink.

7 Responses to Decoding jQuery – Callbacks Object

  1. Pingback: Javascript JQuery var $varname is not a PHP variable! « Code Green Unexposed

  2. Pingback: Linkdump for May 15th | found drama

  3. Allen says:

    Hi Shi. I’m a content curator at DZone and I’m really interested in your blog and I’d like to talk to you about our Most Valuable Blogger program. If you’re interested, send me an e-mail at allenc[at]dzone[dot]com and I’ll give you the details!

  4. Your article is very vivid, thank you for sharing, let me benefit, will continue to focus on your article and look forward to new works.

  5. GordonFus says:

    тут на нашем магазине вы сможете заказать запчасти для espero .

  6. The actual Zoysia InformationThe option is actually your decision, however if you choose to proceed the actual DO-IT-YOURSELF path, right here an excellent, easy formula We combined with excellent achievement. You receive 10 gallons with regard to $1. twenty one. two. ) Fill up the 5 gallon pail halfway along with warm plain tap water. Include the actual dissolved cleaning soap, cleaning soda pop as well as Borax. Mix till natural abercrombie and fitch outlet online powder is actually mixed. Fil

  7. Hello! I know this is kind of off topic but I was wondering which blog platform are you using
    for this site? I’m getting fed up of WordPress because I’ve had issues with hackers and I’m looking at
    alternatives for another platform. I would be awesome if you could point me in the direction of a good platform.

    My web page; Traducciones profesionales ingles español

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>