如何在Meteor中更改变量时生成响应式UI?

时间:2013-08-25 18:06:12

标签: javascript meteor

我不确定我是否理解如何让我的网络应用程序对Meteor保持反应。

我有这个非常简单的模板

<body>
{{> simple}}
</body>

<template name="simple">
    Counter: {{counter}} <br/>
    <button>Increase</button>
</template>

客户端脚本

var counter = 0;

Template.simple.counter = function () {
    return counter;
}

Template.simple.events({
    'click button': function () {
        counter++;
        console.log("counter is ", counter);
        Meteor.flush();
    }
});

单击按钮时,我可以在控制台中看到counter变量正在正常增加但UI上没有任何变化。为什么?我认为这正是Meteor.flush()的目的。

3 个答案:

答案 0 :(得分:4)

UI本身并不具有反应性,您需要使用Meteor的反应项之一。在这种情况下,您可能希望使用Session。请尝试以下操作,而不是您粘贴的第二个脚本:

Session.set('counter', 0); // Initialize a *reactive* variable

Template.simple.counter = function () {
    return Session.get('counter'); // This will automatically update, because Session is reactive
}

Template.simple.events({
    'click button': function () {
        Session.set('counter', Session.get('counter') + 1);
    }
});

答案 1 :(得分:3)

您还可以构建自己的反应式数据源:

if (Meteor.isClient) {
  Sort = {
    sort: 1,

    dep: new Deps.Dependency,

    get: function () {
      this.dep.depend();
      return this.sort;
    },

    toggle: function () {
      this.sort *= -1;
      this.dep.changed();
    }
  };

  Template.leaderboard.players = function () {
    return Players.find({}, {sort: {score: Sort.get(), name: 1}});
  };

  Template.leaderboard.events({
    'click input.sort': function () {
      Sort.toggle();
    }
  });

}

答案 2 :(得分:0)

Meteor的最新版本提供reactive-var包,请参阅此处:http://docs.meteor.com/#/full/reactivevar_pkg

  

要使用ReactiveVar,请在终端中运行将reactive-var软件包添加到项目中:

meteor add reactive-var