【问题标题】:meteor updating template from event来自事件的流星更新模板
【发布时间】:2016-01-05 18:10:37
【问题描述】:

我刚开始使用 Meteor,我真的很喜欢它,但我认为我在处理模板和事件时做错了,感觉不是很被动。

在我的事件中,我有类似的东西

Template.login.event({
   'submit form': function(e, t){
      var password = t.find('#password').value;
      if (password.length < 5) return t.find('#error').innerHTML = 'password too short';

    // a bunch more stuff to handle success cases -- not important for this example
   }
});

在我的模板中,我有

<template name="login">
  <span id="error"></span>
  <form>
    <input name="email" type="email" />
    <input name="password" type="password" id="password" />
  <form>
</template>

我想我应该能够以某种方式说出类似的话 t.data.error = 'password too short 所以我正在更新模板中的数据,并使用 &lt;span id="error"&gt;{{error}}&lt;/span&gt; 而不是直接更新 html,但我似乎找不到如何做到这一点。

【问题讨论】:

    标签: javascript templates meteor


    【解决方案1】:

    您将需要一个反应变量来将助手/事件粘合在一起。最简单的方法是使用Session,虽然我个人不喜欢它,因为它的全球范围

    Template.login.event({
       'submit form': function(e, t){
          e.preventDefault(); // should stop the form submission, check the condition and then continue with the submission if validation is correct
          var password = t.find('#password').value;
          if (password.length < 5) Session.set('error', "password too short");
       }
    });
    
    Template.login.helpers({
        isFormInValid: function(){
            return Session.get('error') != null;
        },
        errorMsg: function() {
            return Session.get('error');
        }
    }); 
    
    {{#if isFormInValid}}
    <span id="error">{{errorMsg}}</span>
    {{/if}}
    

    【讨论】:

    • 只需将Session 替换为在onCreated 中创建的ReactiveVar。几乎和使用Session 一样简单。 :)
    • 是的。我知道ReativeVar。实际上,我在参与的所有项目中都没有使用过Session ;)
    猜你喜欢
    • 1970-01-01
    • 2014-10-16
    • 2015-05-07
    • 1970-01-01
    • 2013-02-07
    • 2013-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多