【问题标题】:Session.get does not set variable in Meteor.jsSession.get 没有在 Meteor.js 中设置变量
【发布时间】:2013-12-07 13:22:08
【问题描述】:

fruit 是模板助手Template.fruits.nameTemplate.fruits.nick 之间共享的变量,以防止在每个单独的助手函数中重复代码。

但是,当change #fruit-selector 事件处理程序被触发时,共享变量fruit 不会改变,即使它由Session.get('fruit') 设置。

这是否意味着我不能使用这种声明 fruit 变量的方法,如果我希望它是反应式的?

ma​​in.js

(function() {

    // Set default fruit
    if(!Session.get('fruit')) {
        Session.set('fruit', 'apple');
    }

    var fruit = Session.get('fruit');


    Template.fruits.name = function() {
        return fruit;
    };

    Template.fruits.nickname = function() {
        return fruit + 'y';
    };

    Template.fruits.name2 = function() {
        return Session.get('fruit');
    };


    Template.fruits.events({
        'change #fruit-selector': function(e) {
            Session.set('fruit', e.target.value);
            console.log('fruit: ' + fruit)
        }
    });

}());

【问题讨论】:

    标签: javascript node.js meteor handlebars.js


    【解决方案1】:

    您必须在模板助手中使用Session.get('fruit'),否则它们不会响应更改(fruit 不是响应式数据源,它从响应式数据源中获取值)。

    PS 使用Session.setDefault('fruit', 'apple'),而不是您的方法。

    【讨论】:

      【解决方案2】:

      试试这个(你是说 Template.fruit.nickname 还是 Template.fruits.nickname?):

      (function() {
      
          // Set default fruit
          if(!Session.get('fruit')) {
              Session.set('fruit', 'apple');
          }
      
          Template.fruits.name = function() {
              return Session.get('fruit');
          };
      
          Template.fruit.nickname = function() {
              return Session.get('fruit') + 'y';
          };
      
          Template.fruits.name2 = function() {
              return Session.get('fruit');
          };
      
      
          Template.fruits.events({
              'change #fruit-selector': function(e) {
                  Session.set('fruit', e.target.value);
                  console.log('fruit: ' + Session.get('fruit'))
              }
          });
      
      }());
      

      【讨论】:

        【解决方案3】:

        看起来,会话不再是默认流星包的一部分。 转到命令提示符并运行“流星添加会话”

        【讨论】:

          猜你喜欢
          • 2013-12-06
          • 1970-01-01
          • 2021-12-27
          • 1970-01-01
          • 2010-10-14
          • 1970-01-01
          • 1970-01-01
          • 2014-01-29
          • 1970-01-01
          相关资源
          最近更新 更多