簡體   English   中英

在底線中使用_.each調用骨干對象中的方法

[英]calling a method in backbone object with _.each in underscore

我是骨干,Javascript,jQuery noob,正在嘗試解決問題。 在我的骨干網視圖中,我有以下方法:

    setError: function (selection, text) {
        console.log("set error");
        this.$el.find(selection).html(text);
        this.$el.find(selection).show();
    },

我想從填充錯誤字段的另一個方法調用此方法,並在div中附加其他消息。 所以我嘗試像這樣調用setError:

     populateErrors: function (sampleErrors) {
       console.log("populateErrors");
        _.each(sampleErrors, function (sample) {
            // Set the error
            this.setError('#sample-error', 'test');
            $('#sample-validation-form').append('<p>testing</p>');
        }, this);
    }

我不明白的是如何調用setError。 因此,如果我在_.each語句之外調用它,則可以執行this.setError。 這對我來說很有意義,因為我正在使用此Backbone對象調用setError。 至少這就是我的解釋方式。 如果不正確,請通知我。

但隨后在_.each聲明,我想,既然我有約束力的聲明this為最后一個參數,我想我不需要this在SETERROR面前。 但是當我嘗試這樣做時,我得到了setError未定義。 因此,我嘗試this.setError如上所示的this.setError ,但是沒有像在_.each循環之外調用this.setError那樣獲得“測試”輸出。 有人可以向我解釋此函數上下文在此示例中如何工作。 我很困惑! 提前致謝!

當您將對象foo作為第三個參數傳遞時,您在說:在匿名函數中, this應該是foo

populateErrors: function (sampleErrors) {
    // `this` is the Backbone view here
    this.setError('#sample-error', 'test');

    _.each(sampleErrors, function (sample) {
        // since you passed the view (this) to `each`
        // `this` is the Backbone view here also
        this.setError('#sample-error', 'test');
    }, this);
}

_.each的第三個參數是上下文。 javascript函數的上下文是對函數中“ this”的引用。 通過傳遞“ this”,您可以保留當前上下文。

例如:

populateErrors: function (sampleErrors) {
   var x = {
          blah: "x context"
       };

   this.blah = "orig context";

   console.log("populateErrors");

    _.each(sampleErrors, function (sample) {
        // Here, your current context is the same context as 
        // when you called populate Errors
        // this.blah === "orig context";
    }, this);

    _.each(sampleErrors, function (sample) {
        // Here, you've defined a different context.
        // this.blah === "x context";
    }, x);
}

您只有一次可以避免使用“ this”。 表達式前面是您使用“ with”關鍵字時。 參見https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/with

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM