2016-01-05 113 views
0

我刚开始使用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

您需要一个反应变量来将帮助者/事件粘合在一起。最简单的方法是使用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}} 
+1

只是在'onCreated'创建'ReactiveVar'更换'Session'。几乎与使用'Session'一样简单。 :) – chrisklaussner

+0

是。我知道'ReativeVar'。实际上,我从未在所有与我合作过的项目中使用过'Session';) –