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. If you’re enjoying carpet installed, Stainmaster
    carpet can be a more sensibe choice since to help you prevent the caqrpet looking different for
    longer. Overhead light is just too harsh and flat.
    Bamboo is another popular choice, costing $4-$6 per square foot.
    The wood then adheres to the sticky upper side of
    the underlay. Let it sit at least for ann hour, but you can also
    leave it overnight.

    Wearing blond hairstyles can just mean that you
    are fun and like trying new things, and iit can just be like wearing a new fun pair of eccentric designer shoes.
    To decorate a classic bedroom with a welcome sight, instead of having a bench, put in an ornate settee at the foot of the bed.

    If you want to crsate an elegant look to your room, then a designer rrug
    is the perfect choice. For example, curtains in turquoise or violet well complement sofaas in stark
    white upholstery. Your carpet has got any stains and you are looking to replace your old and worn out carpet.

    We can also redye a carpet mat to give it a new look, which will
    save car owners money since they don’t need to purchase a new one.

    Holes may be cased due to thee placemnt of heav furniture
    on the carpet, or because of a burn. Shag carpeting tends to have big, bulky yarn whereas,
    frieze has tightly crimped and high twist amounts in the
    luxury carpes yarn system. These underlays can reduce the sound
    going through the floor down to 22db, which is extremely good.
    Carpet dyes are popularly used too give a refreshed look to the interiors of

    Immediately, follow this up with scrubbing out the stains witfh the help of a wwet wash
    cloth. These products are not designed to kill living organiosms like fungi.
    After using a fabric in a room, never use it again anywhere
    else in your house. Vacate the Space- If thhe fumes are really impossible for you oor a family membwr to
    live with, use it as aan excuse too goo on a
    vacation. Afterwards, they use more fungicide and add deodorant too
    the carpet to maoe it smell good.

    We are a fully licensed and certified famly operated
    business. Here are four reasons tto consider making carrpet your flooring of choice.
    Color One of the great perks to investing in replacement caarpet kits for your car is that you can create the ultimate
    custom feel for your caar bby experimenting with color choices for your carpet.

    Professional Fitting A professionally fitted carpet will be cut and laid to
    match the exaqct size of your room. Washable accent ruhs can do
    wonders for your old carpets orr carpeting.

    Don’t hang a mirror between windows, because
    this would create distracts from the view. Call us today to make your car look as good as
    it can. Thiis will ensxure that you gget a bright
    lopk on the carpet. Following around 10 years, the Scotchgard
    goes away aand needs too become reapplied. A person can buy good quality cheap underlay online where
    there is an abundancee oof underlay varieties and types.

    This will insure that your carpets are custom made, with the mokst attractive
    fit. Both of these treatments can assist your arpet keep looking as gooid as innovative for some time, but they alll have some disadvantages and benefits.
    Be sure to launch a website along with thee opening of your new buxiness so that you
    ccan draw more exposure to your business.
    Blot it wijth a napkin or a damp cloth. To create a rustic countryside bedroom, keep the bed, bench, nightstand aand dresser in light colored
    wood, with woioden laminate flooring made of pine or

    If you hav a painting that looks too small above your sofa,
    don’t cejter it. Loose carpwts wear more quickly and could also cause a trip hazard.
    If people wnt a completely different carpet, I usually
    send them to an interior restoration shop.
    In fact, if yoou can spray the mixture and scrubb side by side,
    it wkll give an even better result. This solution is also suitable for colored carpets.

    Since its launch inn 2005, The Maruti Swifvt has received quite a few
    commendations from car enthusiasts and reviews.

    You coiuld go in for themes. By using your
    remnwnt pieces in those areas you extend the look annd
    life of your wall to wall carpet.Do you have
    small children? Try to shut off forced air heating and air conditioning systems to
    prevent the fumes from being circulated to all parts of your space.

    What’s more, wool carpets, because of thedir cushy, malleable
    quality, are also uicker to wear than other fabric types,
    making them look old before their time.

    If yyou are experiencing nausea watering eyes, dry or sorre throat,
    and headaches that won’t quit, you may bee reacting to the airborne chemicals that are off
    gassing from the carpet. You can stick to the same shade or go for a completely neew colored dye
    for auto carpets. Customers of Steamersxpress are assured oof environmentally safe cleaning products used in the cleaning
    process. Remove paint with extreme care as there is often a chance of damaging the carpet.
    Then, in case, there is a stain, you will only have to deal with it, and not other collected dust and
    dirt, which may surface in the process of carpet stain removal.

    Competitors may be very higvh with almost eaqch Multi Nationwide Car Firm investing on the car business within the
    country. Allo the glue to dry overnight, and thdn proceed to vacuum or tread that area.
    New carpet can make any space look luxurious, and feel soft and beautiful under ykur feet.
    Cleaning and Care Once you have had your carpets fitted you ddo need to care for them
    well to ensure they last for as long as possible.

    Professional cleaning products are designed to remove stains
    and odors. Identify the material your carpet is made of (wool, silk,
    cotton, or other fibers), before opting for different products
    and methods to clean it. Place the sconce beside of tthe mirror and it will provide a mokre flattering and natural light.
    All you need to do is sprinkle baking soda on the stain. Remove the Aiborne Chemicals- Using
    a chemicals air purifier to remove the fumes is a cost effehtive waay
    to minimize thhe odors right from the start particularly if you are unable
    to ventilate because the weather iss extremely cold or hot.

    Instead of fitting in excesss small pieces like a sofa, an ottoman, a coffee
    table annd chairs, try installing a larger size of
    sectional, a single table or bench, and an accent chair.
    However, if you are susceptible to mold allergies yoou need to be careful about the pieces you bring into your home.
    It is also called latex paint or emulsion. These are proven to absorb the nasty odors
    of the new carpet. Are yyou planning to create a home with personality and
    style that suiots you and your family?

    my blog; best carpet installation

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>