Imagine I have a session variable that holds an image source. Every second, I want to the helper that contains this session to run.
if (Meteor.isClient) {
Template.TargetTask.helpers({
'imageSrc': function (e, template) {
var clock = setTimeout(function() {
var position = IMAGE_POOL.pop();
Session.set("currentTarget", position);
}, 1000);
var position = Session.get("currentTarget");
var imageSrc = '/' + position + '.bmp';
return imageSrc;
}
});
the image sources are coming from a global IMAGE_POOL
. However, it is possible that the pool contains two same images consecutively. In this case, Session.set()
will be called with the same argument and the session will remain unchanged.
Q1. When Session variable remains unchanged, does the template helper not autorun even if Session.set()
is called?
Q2. If so, how should I make it run every time a new image is popped?
答案 0 :(得分:1)
不,如果值没有变化,则Tracker
计算不会失效。
Session.set('test', false);
Tracker.autorun(function() { console.log(Session.get('test')) }); //Logs 'false'
Session.set('test', false); //Nothing
Session.set('test', true); //Logs true
在你的情况下,如果你想保留这个代码结构(这对我来说似乎有点沉重),你可以改为存储一个带有时间戳的对象:
if (Meteor.isClient) {
Template.TargetTask.helpers({
'imageSrc': function (e, template) {
var clock = setTimeout(function() {
var position = IMAGE_POOL.pop();
Session.set("currentTarget", {
position : position,
timestamp : Date.now()
});
}, 1000);
var position = Session.get("currentTarget").position;
var imageSrc = '/' + position + '.bmp';
return imageSrc;
}
});
}