2016-12-15 25 views
0

我正在使用Meteor 1.4。this.subscribe和Template.instance()。subscribe不起作用

Template.showProducts.onCreated(() => { 
    var handle = Meteor.subscribe("products"); 
    //not working: var handle = this.subscribe("products"); 
    //not working: var handle = Template.instance().subscribe("products"); 

    Tracker.autorun(() => { 
    //not working: this.autorun 

    const isReady = Meteor.ready(); 
    //not working: this.subscriptionsReady() 

    if(isReady){ 
     const products = Products.find().fetch(); 
     Session.set("prods", products); 
    } 
    }); 
}); 

如果我使用 「this.subscribe」,我得到:

Uncaught TypeError: _this.subscribe is not a function

如果我使用 「Template.instance()」,我得到:

Cannot read property 'subscriptionsReady' of null

回答

2

如果使用一個箭頭函數,那麼流星嘗試傳入的值this就會丟失。請使用常規的匿名功能(function() { ... })。

你應該再使用this.autorun而非Tracker.autorun。這將確保自動運行在模板消失時被清除,並允許Template.instance在自動運行中工作。

2

問題是您正在傳遞onCreated處理程序的箭頭函數,該函數不允許綁定thisreference)。因此,Meteor無法正確綁定它剛剛創建的模板實例,並且您的訂閱(以及其他各種事物)將會失敗。

的修復程序只是爲了打發onCreated傳統的JS功能:

Template.showProducts.onCreated(function() { 
    ...