Print Shortlink

Callbacks() in jQuery

There are different operations that you want to perform on some data. The functionalities that you want to perform will depend on the user input or actions. Now, the implementation looks like normal function calls based on some conditions. Things can get tedious if the number of operations increases, though. The Callbacks() in jQuery provides a sophisticated approach for handling this.

jQuery provides a $.Callbacks() method that can be used to hold a list of callback functions. The functions can be added and removed at will. You can fire the functions at one shot by passing in the data.

Say you have three functions add, subtract and multiply as shown below.

function add(a,b){
	console.log(a+b);
}
function subtract(a,b){
	console.log(a-b);
}
function multiply(a,b){
	console.log(a*b);
}

You can add these function to $.Callbacks() object using add() method and fire them all by passing the numbers using fire() method as shown below.

var operations = $.Callbacks();
operations.add(add);
operations.add(multiply);
operations.add(subtract);
operations.fire(20,30);//invokes all the methods

Callbacks() also has few more useful methods like remove(), fireWith() etc that you can read from the jQuery documentation.

You can view this example with UI and conditions here. Play with this example by only providing valid numerical data :)

Leave a Reply