[英]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.