简体   繁体   English

带回调的jQuery简单函数

[英]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...我正在尝试写下一个函数,该函数将执行某些操作,然后在完成后绑定回调,我想在初始化 js 函数时指定回调...

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.请注意,在 JavaScript 中有更好的方法来执行该回调,例如.apply()call() ,但只有当您计划在回调中使用 this 关键字时才需要这样做

Inside of the function that you pass a function to, you have to invoke the passed function ie在您传递函数的函数内部,您必须调用传递的函数,即

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()在使用Function.prototype.apply()Function.prototype.call()调用回调函数时,您可能会更进一步并为其提供不同的上下文

http://jsfiddle.net/wsNzL/ http://jsfiddle.net/wsNzL/

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM