Skip to content
For the complete documentation index, see llms.txt. This page is also available as Markdown.

Callbacks

The $.Callbacks object

Callbacks is a really cool object. It lets you create lists of callback functions and gives you full control over them. It's simpler to work with than Deferred — there's no separation into positive and negative scenarios. Just a stack of functions that gets executed on the fire() command:

var C = $.Callbacks();

C.add(function(msg) {
    console.log(msg + " first")
});

C.add(function(msg) {
    console.log(msg + " second")
});

C.fire("Go");

If you open the console and run the script above, you'll get something like this:

>>>
Go first
Go second

— Where's the power, bro? — In the arguments.

By default, you can call the fire() method over and over again right from the console, and you'll get the same result every single time. But you can also define the Callbacks behavior through flags:

flag
description

once

all functions will be called only once (similar to the Deferred object)

memory

stores the value from the last fire() call and feeds it to newly registered callback functions, only then processes the new value (that's exactly how Deferred works)

unique

the callback function list is filtered for uniqueness

stopOnFalse

as soon as any function returns "false", the firing process stops

Probably better with examples, here's once:

The memory flag is a bit trickier, pay attention:

The unique example is dead simple:

The stopOnFalse flag:

You can combine these flags and get interesting results, or you can skip that and just look at the following example. Here's the page to work with:

Add movement commands for the car in any order and quantity. To do this, run the scripts listed below (nothing will happen with the car until you call the fire() method):

Let's go!

A bit of history: the "Deferred" object branched off from the $.ajax() method as a result of jQuery 1.5 refactoring. Time passed, new versions of jQuery came out, and another round of refactoring happened — resulting in "Callbacks" being separated from "Deferred" in version 1.7. So in the current version of the library, the $.ajax() method works with the "Deferred" object, which is a layer on top of "Callbacks". To avoid confusion in terminology, I use the term "Deferred Callbacks" when working with "Callbacks" too, because there are many callbacks out there, and clarifying every time that I mean "that particular one" is quite tiresome.

Here's an article on this topic that I recommend — Async JS: The Power of $.Deferred

Last updated