How to Add a Function to a jQuery Callbacks List

The jQuery $.Callbacks() object provides a multi-purpose callback list system used internally by components like $.ajax() and $.Deferred(). This article explains how to add functions to a jQuery Callbacks list using the built-in .add() method, walks through a basic code implementation, and covers how to add multiple functions or configure list behaviors.

Using the callbacks.add() Method

To add a function to a jQuery Callbacks list, use the .add() method on a Callbacks instance. The method accepts a function, an array of functions, or a list of function references separated by commas.

Basic Example

To get started, instantiate the callback object using $.Callbacks(), define your function, and pass it to the .add() method:

// 1. Create a Callbacks instance
const myCallbacks = $.Callbacks();

// 2. Define a function
function greet(name) {
    console.log("Hello, " + name);
}

// 3. Add the function to the list
myCallbacks.add(greet);

// 4. Execute the list
myCallbacks.fire("World"); // Output: "Hello, World"

Adding Multiple Functions

The .add() method is flexible and allows you to attach multiple functions at once or chain method calls together.

1. Passing an Array of Functions

You can pass an array containing multiple function definitions or references:

function stepOne() {
    console.log("Step 1 complete");
}

function stepTwo() {
    console.log("Step 2 complete");
}

myCallbacks.add([stepOne, stepTwo]);
myCallbacks.fire();

2. Method Chaining

Because .add() returns the callback object itself, you can chain multiple .add() calls:

myCallbacks.add(stepOne).add(stepTwo);

Controlling Behavior with Flags

When initializing $.Callbacks(), you can supply flags as strings to control how functions are added and executed:

  • "unique": Prevents duplicate functions from being added to the list.

    const uniqueCallbacks = $.Callbacks("unique");
    uniqueCallbacks.add(greet);
    uniqueCallbacks.add(greet); // Ignored; will not execute twice
  • "memory": Remembers the most recent arguments passed to .fire(). If a new function is added via .add() after the list has already been fired, the newly added function executes immediately with the stored values.

    const memoryCallbacks = $.Callbacks("memory");
    memoryCallbacks.add(greet);
    memoryCallbacks.fire("Alice"); // Output: "Hello, Alice"
    
    // Adding a new function executes immediately with "Alice"
    memoryCallbacks.add(function(name) {
        console.log("Welcome, " + name);
    }); // Output: "Welcome, Alice"
  • "once": Ensures the list can only be fired once.

  • "stopOnFalse": Halts callback execution across the entire list if any added function returns false.