在JavaScript中创建自定义回调

本文翻译自:Create a custom callback in JavaScript

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? 我该如何实现?


#1楼

参考:https://stackoom.com/question/9BwI/在JavaScript中创建自定义回调


#2楼

It is good practice to make sure the callback is an actual function before attempting to execute it: 在尝试执行回调之前,确保回调是实际函数是一种好习惯:

if (callback && typeof(callback) === "function") {

  callback();
}

#3楼

My 2 cent. 我2分。 Same but different... 相同但不同......

<script>
    dosomething("blaha", function(){
        alert("Yay just like jQuery callbacks!");
    });


    function dosomething(damsg, callback){
        alert(damsg);
        if(typeof callback == "function") 
        callback();
    }
</script>

#4楼

   function callback(e){
      return e;
   }
    var MyClass = {
       method: function(args, callback){
          console.log(args);
          if(typeof callback == "function")
          callback();
       }    
    }

============================================== ==============================================

MyClass.method("hello",function(){
    console.log("world !");
});

============================================== ==============================================

Result is: 结果是:

hello world !

#5楼

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 基础

function doSomething(callback) {
    // ...

    // Call the callback
    callback('stuff', 'goes', 'here');
}

function foo(a, b, c) {
    // I'm the callback
    alert(a + " " + b + " " + c);
}

doSomething(foo);

That will call doSomething , which will call foo , which will alert "stuff goes here". 这将调用doSomething ,它将调用foo ,它会提醒“东西在这里”。

Note that it's very important to pass the function reference ( foo ), rather than calling the function and passing its result ( foo() ). 请注意,传递函数引用foo )非常重要,而不是调用函数并传递其结果( 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 . 有时你想调用回调所以它看到的特定值this You can easily do that with the JavaScript call function: 您可以使用JavaScript call函数轻松完成此操作:

function Thing(name) {
    this.name = name;
}
Thing.prototype.doSomething = function(callback) {
    // Call our callback, but using our own instance as the context
    callback.call(this);
}

function foo() {
    alert(this.name);
}

var t = new Thing('Joe');
t.doSomething(foo);  // Alerts "Joe" via `foo`

You can also pass arguments: 你也可以传递参数:

function Thing(name) {
    this.name = name;
}
Thing.prototype.doSomething = function(callback, salutation) {
    // Call our callback, but using our own instance as the context
    callback.call(this, salutation);
}

function foo(salutation) {
    alert(salutation + " " + this.name);
}

var t = new Thing('Joe');
t.doSomething(foo, 'Hi');  // Alerts "Hi Joe" via `foo`

Sometimes it's useful to pass the arguments you want to give the callback as an array, rather than individually. 有时,传递您想要将回调作为数组的参数,而不是单独传递是有用的。 You can use apply to do that: 你可以使用apply来做到这一点:

function Thing(name) {
    this.name = name;
}
Thing.prototype.doSomething = function(callback) {
    // Call our callback, but using our own instance as the context
    callback.apply(this, ['Hi', 3, 2, 1]);
}

function foo(salutation, three, two, one) {
    alert(salutation + " " + this.name + " - " + three + " " + two + " " + one);
}

var t = new Thing('Joe');
t.doSomething(foo);  // Alerts "Hi Joe - 3 2 1" via `foo`

#6楼

function LoadData(callback) 
{
    alert('the data have been loaded');
    callback(loadedData, currentObject);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章