2014-10-12 43 views
3

我有以下幾點:如何正確停止Meteor Tracker.autorun?

Meteor.startup(function() { 
    var computation = Tracker.autorun(function() { 
    var currentChapter; 
    currentChapter = Chapters.findOne({ 
     _id: currentChapterId 
    }); 
    if (currentChapter) { 
     if (currentChapter.title) { 
     $("#input-title").val(currentChapter.title); 
     } else { 
     $("#input-title").val(""); 
     } 
     if (currentChapter.content) { 
     $("#input-content").html(currentChapter.content); 
     } else { 
     $("#input-content").html(""); 
     } 
    } 
    return computation.stop(); 
    }); 
}); 

現在我得到:

Exception from Tracker afterFlush function: Cannot call method 'stop' of undefined TypeError: Cannot call method 'stop' of undefined

我想要做的是立即停止計算currentChapter是真實的。我究竟做錯了什麼?

+0

我會在遊標上使用[observe method](http://docs.meteor.com/#observe),而不是在你的情況下使用'Tracker.autorun'。 – 2014-10-12 10:28:17

+0

@Peppe L-G爲什麼要使用observe? – alexchenco 2014-10-12 11:21:22

+0

我會主要使用觀察回調來使代碼更具可讀性,但我認爲它的執行速度會更快,並且會稍小一些。 – 2014-10-12 13:25:01

回答

4

兩件事情:

1 - 你的自動運行功能得到一個句柄傳遞給它的計算,這樣你就可以像這樣停止它:

Meteor.startup(function() { 
    var computation = Tracker.autorun(function(thisComp) { 
    var currentChapter; 
    currentChapter = Chapters.findOne({ 
     _id: currentChapterId 
    }); 
    if (currentChapter) { 
     if (currentChapter.title) { 
     $("#input-title").val(currentChapter.title); 
     } else { 
     $("#input-title").val(""); 
     } 
     if (currentChapter.content) { 
     $("#input-content").html(currentChapter.content); 
     } else { 
     $("#input-content").html(""); 
     } 
     thisComp.stop(); 
    } 
    }); 
}); 

2 - 在你的代碼,計算會不管 - 你應該在if (currentChapter)區塊內停止它,在第一次運行結束時停止。

+0

「Tracket.aurotun」的返回值應該與您的'thisComp'參數相同。 – 2014-10-12 10:26:04

+0

對不起,Peppe L-G,我不明白 - 你能解釋一下嗎? – richsilv 2014-10-12 10:29:22

+0

@ PeppeL-G'thisComp'來自'function'的第一個參數,我認爲Meteor也加入了這個(以及返回值) – Akshat 2014-10-12 11:05:22