来自事件的流星更新模板

时间:2016-01-05 07:08:37

标签: javascript templates meteor

我刚刚开始使用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所以我要更新模板中的数据,并使用<span id="error">{{error}}</span>而不是直接更新html,但我似乎无法找到如何做到这一点。

1 个答案:

答案 0 :(得分: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}}