2014-01-24 42 views
0

我正在構建一個使用流星的在線測驗系統。預計測驗中的每個用途都有自己的計時器,設置爲一個小時。計時器應該在用戶首次登錄時啓動。 我目前正在維護一個名爲UserClocks(userId,timeLeft)的集合。流星個人用戶計時器 - setInterval()

我寫了的setInterval這樣

var interval = Meteor.setInterval(function() { 

    console.log("User id: " + this.userId); 
    console.log("Searching clock for: " + clocksMap[this.userId]); 
    //clocksMap contains the _id of the UserClocks. 
    var userClock = UserClocks.find({_id: clocksMap[this.userId]}); 

    if (!!userClock) { 
     console.log("Found clock: " + userClock.timeLeft); 
    } else { 
     console.log("Clock not found for user: " + this.userId); 
    } 

    var time = userClock.timeLeft; 
    time = time - 1; 
    UserClocks.update(userClock._id, {timeLeft: time}); 
    console.log("Updated userClock. timeleft: " + time); 

    if (time === 0) { 
     //logout user and clear interval 
     Meteor.clearInterval(intervalMap[this.userId]); 
    } 

}, 1000); 

此的setInterval()是一個被稱爲B中的用戶的方法的內部。 由於userClock未定義,我一直將timeLeft設置爲NaN。 我想我明白了爲什麼我不能在setInterval()中使用this.userId,但我需要解決我的問題。我怎樣才能爲每個用戶分別設置計時器?

+0

我也嘗試了userId從方法的參數到.find()。它仍然返回未定義timeLeft! – Pawan

+0

如果用戶進入控制檯,UserClocks.update(userClock._id,{timeLeft:999999})''怎麼辦? –

+0

我試過了,但沒有定義。但是,UserClocks.find({_ id:「o8y5nw4Wp5H7SF8bP」)返回LocalCollection.Cursor。我正在使用不安全的軟件包,並將我的UserClocks放入我的model.js中共享 – Pawan

回答

1

將此代碼放在Meteor.methods區塊內。您可以在setInterval函數中使用Meteor.userId(),但不能使用this.userId。在回調中,this可能會設置爲window,它沒有userId

如果運行這個Meteor.publish回調中,存儲userId事先:

var userId = this.userId; 

Meteor.setInterval(function() { 
    clock = UserClocks.find({_id: userId}); 
    // Do stuff 
} 

我會建議,正如你看到的上面,是剛剛的文檔存儲在UserClocks要麼_id或其他的事情userId對應於Meteor.userId()。在集合之外保留單獨的地圖是沒有意義的。

+0

我嘗試了您所提供的內容。 userId在setInterval()的外部和內部工作正常。我也通過將它作爲參數傳遞給方法來嘗試它。這個setInterval已經存在於Meteor.methods塊內部的一個方法中。在嘗試您所建議的內容後,我仍然將timeLeft和clockId設置爲undefined。 – Pawan

+0

輸出:CLock id:5EZgsavncGBBXr8Qj I20140125-02:10:03.546(5.5)?用戶名:JFPfgyeordrME6m4M I20140125-02:10:03.547(5.5)?正在搜索時鐘:5EZgsavncGBBXr8Qj I20140125-02:10:03.547(5.5)?找到時鐘未定義 I20140125-02:10:03.547(5.5)?找到時鐘:undefined I20140125-02:10:03.553(5.5)?更新了userClock。 timeleft:NaN I20140125-02:10:04.551(5.5)?用戶名:JFPfgyeordrME6m4M – Pawan