开发者

jquery - write a function to allow for a callback? [duplicate]

This question already has answers here: Closed 12 years ago.

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!
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜