2015-04-15 94 views
0

我試圖使用Meteor.setInterval函數,但我有一些麻煩使用它。爲什麼使用Meteor.setInterval調用方法會引發TypeError異常?

這裏是我的代碼:

Meteor.methods({ 
    init : function(){ 
    console.log('test'); 
    }, 
    start : function(period){ 
    console.log('start : period '+period); 

    Meteor.setInterval(Meteor.call('init'),period); 
    } 
}); 

Meteor.call('start', 100); 

我看到的 「test」 我的控制檯1次,然後我得到了以下錯誤:

異常中的setInterval回調:類型錯誤:未定義不一個函數。

我一直在看這個問題:Exception in setInterval callback但我做了不同的方式(使用Method.methods)。

發生了什麼,我該如何解決?

回答

2

看這句話:

Meteor.setInterval(Meteor.call('init'),period); 

現在去想想發動機做什麼。首先,Meteor.setInterval。他需要這個功能是:

  • 回調
  • 毫秒數

的你怎麼過?毫秒數,以及通過Meteor.call('init')的回撥。引擎看到你的call,並執行它,因爲這就是你要求他做的括號。而你的通話什麼都不返回。然後setInterval嘗試執行任何操作。

那麼,如何將參數的功能傳遞給Meteor.setInterval?一種方法是將它包裝到一個閉包:

Meteor.setInterval(function() { 
    Meteor.call('init'); 
}, period }); 

這樣,你的call立即執行,當setInterval使用回調,然後執行你call它纔會執行。您也可以部分應用call。有兩種方式:

  1. 母語:

    Meteor.setInterval(Meteor.call.bind(null, 'init'), period); 
    
  2. 隨着_.partial

    Meteor.setInterval(_.partial(Meteor.call, 'init'), period); 
    
+0

謝謝你這麼多的很好的解釋,現在的作品完美:) – TLR

相關問題