开发者

jQuery simple function with callback

I'm trying writing down a function which will do something then bind a callback when finished, I would like to specify the callback when I init the js function...

function hello(arg1,arg2,callback){
    alert(arg1 + arg2);

   callback;
} 

hello('hello','world',function callback(){
    开发者_运维知识库alert('hey 2);
});

sorry for banal question, I'm trying to understand how to pass a callback function to a function.


you need to call that function like anything else:

function hello(arg1,arg2,callback){
    alert(arg1 + arg2);

   callback();
} 

hello('hello','world',function callback(){
   alert('hey 2);
});

Note that in JavaScript there are better ways to execute that callback, like .apply() or call() but that is only required if you plan on using the this keyword inside callbacks.


Inside of the function that you pass a function to, you have to invoke the passed function i.e.

function hello(arg1,arg2,callback){
  alert(arg1 + arg2);

  callback(); // invoke the function (this is just one way)
} 

hello('hello','world', function (){
  alert('hey 2');
});

You might go further and give the callback function a different context when calling it using Function.prototype.apply() or Function.prototype.call()


http://jsfiddle.net/wsNzL/

function A(a,b,func)
{
alert(a+b);
    func();
}

A(1,2,function(){alert("callback called");});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜