[英]Why my helper doesn't re-run when the collection I call inside it is updated?
我有一個帶有視頻播放器的模板。 它使用幫助程序從mongo文檔獲取視頻源。 看起來是這樣的:
幫手:
'currentItemUrl' : function() {
//I only have one project. Is there a better/cleaner way to obtain it than the one below?
var currentProject = Projects.find().fetch()[0];
//the function below will create an instance of videojs or update the current one (set the new source)
loadPlayer();
//I return the source url if I have one
return currentProject.setup.player.item_loaded.url?currentProject.setup.player.item_loaded.url:"";
}
HTML看起來像這樣:
<video id="video_player" class="video-js vjs-default-skin" controls preload="auto"
width = "{{videoWidth}}" height="videoHeight"
poster="{{currentItemPoster}}">
<source id="mp4" src="{{currentItemUrl}}" type='video/mp4' />
<source id="webm" src="" type='video/webm' />
<source id="ogg" src="" type='video/ogg' />
</video>
問題
在另一個模板中更新我的Projects
集合時,如何確保我的助手重新運行? 由於我使用Collection.find()
它不應該已經是反應性的嗎?
至於第一個問題(在代碼的注釋中),如果在任何時間點只有一個文檔,那么findOne
方法要簡單得多:
var currentProject = Projects.findOne();
除了使用笨重的三元數作為缺省值之外,您可以簡單地使用||
操作員 :
//Always place the default on the right, since '' is falsey
return (currentProject.setup.player.item_loaded.url || '');
而且因為您使用find
(或findOne
,除了返回一個文檔,它基本上是相同的東西),所以它將始終是反應性的。 如果文檔發生更改,那么Tracker的計算將無效,您的助手將使用以下計算 :
在后台,每個幫助程序都會啟動一個新的Tracker.autorun。 當其反應性依賴項發生更改時,將重新運行幫助程序。 幫助程序取決於其數據上下文,傳遞的參數以及在執行期間訪問的其他反應性數據源。
但是,正如注釋中的附錄所述,您的助手會引發副作用( loadPlayer()
)-通常認為這是一種不好的做法,因為助手與吸氣劑非常相似:您只希望它返回數據,而不更改任何內容。 您可能要為此作業運行另一個Tracker計算 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.