jquery - write a function to allow for a callback? [duplicate]
Possible Duplicate:
Javascript callback programming?
A lot of jquery functions allow for a callback. Most are in a syntax like:
$('.selector').slideUp('fast', function(){
alert('slideUp has completed');
});
If I'm writing my own function, how can I make sure it is finished b开发者_运维问答efore the one after it is called (i.e. provide a callback parameter)
var foo = function(bar, callback){
console.log(bar);
if(typeof callback == "function"){
callback();
}
};
foo("hello world", function(){
console.log("done!");
});
output
hello world
done!
Alternatively, you can invoke the callback like so
callback.call(this, arg1, arg2);
This will pass the scope of the foo
function (and optional parameters) to the callback function.
var foo = function(bar, callback){
console.log(bar);
if(typeof callback == "function"){
callback.call(this, bar);
}
};
foo("hello world", function(x){
console.log(x + " is done!");
});
output
hello world
hello world is done!
精彩评论