I understand passing in a function to another function as a callback and having it execute, but I'm not understanding the best implementation to do that. I'm looking for a very basic example, like this:
var myCallBackExample = {
myFirstFunction : function( param1, param2, callback ) {
// Do something with param1 and param2.
if ( arguments.length == 3 ) {
// Execute callback function.
// What is the "best" way to do this?
}
},
mySecondFunction : function() {
myFirstFunction( false, true, function() {
// When this anonymous function is called, execute it.
});
}
};
In myFirstFunction, if I do return new callback(), then it works and executes the anonymous function, but that doesn't seem like the correct approach to me.
You can just say
Alternately you can use the
call
method if you want to adjust the value ofthis
within the callback.Inside the function
this
would be whatevernewValueForThis
is.You should check if the callback exists, and is an executable function:
A lot of libraries (jQuery, dojo, etc.) use a similar pattern for their asynchronous functions, as well as node.js for all async functions (nodejs usually passes
error
anddata
to the callback). Looking into their source code would help!There are 3 main possibilities to execute a function:
The method you choose depends whether:
Docs for Function.call, Function.apply
the proper implementation would be:
this makes the callback parameter optional..
You can use:
the below example is little more comprehensive: