2015-06-30 57 views
1

想象一下,我有一個保存圖像源的會話變量。每秒鐘,我想要包含此會話的助手運行。流星模板自動運行(會話變量)

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; 
    } 
    }); 

圖像來源來自全球IMAGE_POOL。但是,池可能會連續包含兩個相同的圖像。在這種情況下,將使用相同的參數調用Session.set(),並且會話保持不變。

Q1。當Session變量保持不變時,即使Session.set()被調用,模板幫助程序是否不自動運行? Q230。 Q2。如果是這樣,每當新圖像彈出時我應該如何運行它?

回答

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; 
    } 
    }); 
}