All I need to do is to execute a callback function when my current function execution ends.
function LoadData()
{
alert('The data has been loaded');
//Call my callback with parameters. For example,
//callback(loadedData , currentObject);
}
A consumer for this function should be like this:
object.LoadData(success);
function success(loadedData , currentObject)
{
//Todo: some action here
}
How do I implement this?
Actually, your code will pretty much work as is, just declare your callback as an argument and you can call it directly using the argument name.
The basics
That will call
doSomething, which will callfoo, which will alert “stuff goes here”.Note that it’s very important to pass the function reference (
foo), rather than calling the function and passing its result (foo()). In your question, you do it properly, but it’s just worth pointing out because it’s a common error.More advanced stuff
Sometimes you want to call the callback so it sees a specific value for
this. You can easily do that with the JavaScriptcallfunction:You can also pass arguments:
Sometimes it’s useful to pass the arguments you want to give the callback as an array, rather than individually. You can use
applyto do that: