【问题标题】:Meteor template autorun (Session variable)Meteor 模板自动运行(会话变量)
【发布时间】:2015-06-30 22:14:28
【问题描述】:

假设我有一个保存图像源的会话变量。每一秒,我都想让包含这个会话的助手运行。

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() 将使用相同的参数调用并且会话将保持不变。

第一季度。当 Session 变量保持不变时,即使调用了Session.set(),模板助手是否也不会自动运行? 第二季度。如果是这样,我应该如何让它在每次弹出新图像时运行?

【问题讨论】:

    标签: meteor


    【解决方案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;
        }
      });
    }
    

    【讨论】:

      猜你喜欢
      • 2014-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-10
      • 2015-05-19
      • 1970-01-01
      • 2015-11-05
      • 1970-01-01
      相关资源
      最近更新 更多