让Meteor每秒更新一个字符串

时间:2013-11-19 09:59:44

标签: meteor setinterval

这是Meteor的默认HTML:

<head>
  <title>random-test</title>
</head>

<body>
  {{> hello}}
</body>

<template name="hello">
  <h1>Hello World!</h1>
  {{greeting}}
  <input type="button" value="Click" />
</template>

这是Meteor默认的Javascript代码:

if (Meteor.isClient) {
  Template.hello.greeting = function () {
    return "Welcome to random-test.";
  };

  Template.hello.events({
    'click input' : function () {
      // template data, if any, is available in 'this'
      if (typeof console !== 'undefined')
        console.log("You pressed the button");
    }
  });
}

if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
  });
}

我更改了Javascript,因此我可以每秒更新{{greeting}}

if (Meteor.isClient) {
  Template.hello.greeting = "hi";

  Meteor.setInterval(function() {
    Session.set("greeting", "hello");
    console.log("Hi");
  }, 1000);

  Template.hello.events({
    'click input' : function () {
      // template data, if any, is available in 'this'
      if (typeof console !== 'undefined')
        console.log("You pressed the button");
    }
  });
}

if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
  });
}

每秒都是console.logging“hi”。但是,它要么不更新greeting的值,要么Session.get不更新它的值(根据Meteor文档)。

2 个答案:

答案 0 :(得分:3)

您需要在帮助程序中返回Session.get('greeting')

Template.hello.greeting = function() {
    return Session.get('greeting');
}

答案 1 :(得分:0)

Template.hello.greeting = "hi";使模板不依赖于Session.get('greeting'),因此对“会话变量”的更改不会导致任何重新渲染。或者你期望发生什么?