I have a template with a video player. It gets the video source from a mongo document, using an helper. Here is how it looks like:
The helper:
'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:"";
}
And the HTML looks like that:
<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>
The question
How can I make sure that my helper is re-run when I update my Projects
collection in another template? Since I use a Collection.find()
shouldn't it already be reactive?
As for your first question (in the comments of your code), if you only have one document at any point in time then there is a much simpler way with findOne
:
var currentProject = Projects.findOne();
Instead of a heavy ternary for your defaulting you could simply use the ||
operator :
//Always place the default on the right, since '' is falsey
return (currentProject.setup.player.item_loaded.url || '');
And because you use find
(or findOne
which is basically the same thing except it returns one document) it will always be reactive. If the document changes, then Tracker computations will invalidate and your helper uses such a computation :
Under the hood, each helper starts a new Tracker.autorun. When its reactive dependencies change, the helper is rerun. Helpers depend on their data context, passed arguments and other reactive data sources accessed during execution.
However, as apendua noted in a comment, your helper triggers side-effects (loadPlayer()
) - This is generally considered a bad practice because a helper is very similar to a getter: You just expect it to return data, not alter anything. You may want to run another Tracker computation for this job.