2016-07-31 95 views
1

對不起,ES6福利局這裏:流星ES6脂肪箭頭功能和`this`在onCreated不工作

Template.hello.onCreated(() => { 
    // counter starts at 0 
    this.counter = new ReactiveVar(0); 
}); 

Template.hello.helpers({ 
    counter() { 
    return Template.instance().counter.get(); 
    }, 
}); 

Template.hello.events({ 
    'click button'(event, instance) { 
    // increment the counter when button is clicked 
    instance.counter.set(instance.counter.get() + 1); 
    }, 
}); 

當我按一下按鈕我得到Cannot read property 'get' of undefined

但是當我做

Template.hello.onCreated(function(){ 
    // counter starts at 0 
    this.counter = new ReactiveVar(0); 
}); 

它工作正常。

因此,我沒有收到關於this關鍵字的ES6胖箭頭綁定的問題。

回答

2

當流星調用onCreated處理函數時,它將函數的this值綁定到模板實例。 Arrow functions詞彙綁定this,這意味着在箭頭函數內的this是相同的功能定義,在您的情況下可能window。因此,您正在創建一個全局變量counter,而不是將其分配給模板實例。

對於onCreated,onRendered等,使用箭頭函數是沒有意義的。

+0

有趣。我認爲箭頭函數是所有*函數需要寫入ES6的方式嗎?這是否意味着在ES6中,您實際上需要考慮使用哪種類型的函數,尤其是在使用'this'時? BTW'計數器'確實是作爲一個全局變量創建的。 – fuzzybabybunny

+0

確切地說,這兩種功能都有自己的用例。有時,你選擇哪一個並不重要,但是'this'上下文由框架提供的回調(如'onCreated')是一個需要「正常」功能的例子。這裏有一篇很好的文章,列出了其他一些案例:https://rainsoft.io/when-not-to-use-arrow-functions-in-javascript/。在我的項目中,我總是使用'函數',除非箭頭函數使代碼更易於閱讀。 – chrisklaussner

+1

Ohhhhhh ....謝謝。超級有價值的信息。 – fuzzybabybunny