在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);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章