【问题标题】:How to update a Handlebars template variable only on client-side using Meteor?如何仅在客户端使用 Meteor 更新 Handlebars 模板变量?
【发布时间】:2013-11-22 01:46:10
【问题描述】:

我想学习如何在客户端更新模板中的单个项目。如果可能,请提供 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

    }

  });  

}

谢谢。

【问题讨论】:

    标签: meteor handlebars.js


    【解决方案1】:

    反应性

    将响应式源视为“来自函数的值,这些函数在每次更新时都会重新运行以生成值”。在此示例中,我们使用响应式源(会话值)向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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多