如何使用Meteor仅在客户端更新Handlebars模板变量?

时间:2013-11-21 17:02:55

标签: meteor handlebars.js

我想学习如何在客户端更新模板中的单个项目。如果可能,请提供Session和MongoDB的示例。

我最简单的模板文件:

<template name="teste">
  <input type="button" value="Set one item" class="setitem" /><br><br>
  {{item1}}
</template>

在我的JS文件中,我有:

if (Meteor.isClient) {

  Template.teste.events({

    'click .setitem' : function () {

      // What I put here to update the {{item1}}:

      // 1. Not Reactive (only on client)
      // 2. Reactive with Session
      // 3. Reactive with MongoDB

    }

  });  

}

感谢。

1 个答案:

答案 0 :(得分:3)

活性

将反应源视为“来自重新运行的函数的值,以便在每次更新时生成值”。在此示例中,我们使用反应源(会话值)为item1提供值。更改值会触发重新计算item1,从而立即为模板生成新值。

// Supplying item1 from a reactive source (Session)
Template.teste.item1 = function(){
  Session.get('item1');
}

// Place this in the click handler
Session.set('item1','some_value');

非反应性

对于不使用反应源的值,不会自动重新运行这些功能。在以下示例中,我们使用普通变量_item1来提供数据。为了反映_item1item1的变化,我们创建了一个Dependency对象,我们可以在其中绑定函数,这样当触发Dependency对象的更改时,它会重新运行所有绑定函数。

// A variable storing our real value. A non-reactive source.
Template.teste._item1 = '';
//Dependency object
Template.teste._item1Deps = new Deps.Dependency;

Template.teste.item1 = function(){
  // Bind the enclosing function to the Dependency object
  Template.teste._item1Deps.depend(); 
  return Template.teste._item1;
}

//In your handler
Template.teste._item1 = 'some_value'; //Change value does not trigger reactivity
Template.teste._item1Deps.changed();  //Rerunning all functions bound to the object