JS- Callback

A callback function, also known as a higher-order function, is a function that is passed to another function (let’s call this other function “otherFunction”) as a parameter, and the callback function is called (or executed) inside the otherFunction.

This can be useful when you are trying to execute two functions that are dependent in one another.


  • JQuery uses a lot of callback functions without us realizing it.
 JQuery Click example 
$('#btn').click(function(){
    console.log("Button clicked");
});

In the example above we are passing in an anonymous function into the click function. Somewhere inside the click function our anonymous function will execute.


  • Another example is the foreach function
Foreach Example
var names = ["A","B","C","D"];

names.foreach(function(name,index){
     console.log(index + " " + name);
});

We are passing in again an anonymous function into the foreach function to execute the console.log message.


To write a callback function all you need to do it create 2 functions and pass one function as a parameter into the other.

//A general output message function
function OutputMessage(data)
{
    if (typeof data === "string")
    {
       console.log("This is a string: " + data);
    }
    else if (typeof data == "object")
    {
       console.log("This is a object);
       for(var item in data)
       {
           console.log(item + " " + data[item]);
       }
    }

}

//Function to take in the callback function
var InputMessage(userData, callback)
{
    console.log("Going to execute the function now");
    callback(userData);
}

//So now to call the function and see what will happen
InputMessage({name:"A",age:"27"},OutputMessage)
//Result:
//This is a object
//name A
//age 27
InputMessage("String Message",OutputMessage)
//Result:
//This is a string: String Message

The example above shows how to pass a function into another function as a parameter


One problem that people face when using callback functions is preserving ‘this’
The example below will show how this can be done:

//An Object that has a function inside to set the first and last names
var obj = {
firstName: "A",
lastName: "B",
SetName: function(first,last)
{
   this.firstName = first;
   this.lastName = last;
}}; 

function UserInput(firstName,lastName,callback)
{
    callback(firstName,lastName);
}
//When using the function UserInput to call obj's function directly
//you will not get the correct result
UserInput("C","D",obj.SetName);
//The this in this case will mean the global windows variables.
console.log(window.firstName + " " + window.lastname); //C D

//Instead you need to pass the correct this into the function to do this
//you need to change the functions a little
function UserInput(firstName,lastName,callback,callbackObj)
{
    callback.apply(callbackObj,[firstName,lastName]);
}
//Now this will use the obj as the correct this
UserInput("C","D",obj.SetName,obj);
//This will now edit the variables inside the obj
console.log(obj.firstName + " " + obj.lastName)// C D

http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s