从两个文本框中获取值,并在meteor.js中显示模板上的值

时间:2015-02-05 11:33:47

标签: meteor

我尝试使用meteor.js在模板页面中显示总和值。

这是我的HTML代码:

<head>
    <title>Sum</title>
</head>
<body>
    <h1>Sum of two values</h1>

    {{> sumForm}}   
</body>

<template name="sumForm">
    <form>
        <input type="text" name="value1"> + <input type="text" name="value2"><p>Total: {{totalSum}}</p>
        <input type="submit" value="Sum">
    </form>
</template>

和我的js代码:

if(Meteor.isClient){

    Template.sumForm.events({

        'submit form': function(event){
            event.preventDefault();

            value1Var = parseInt(event.target.value1.value);
            value2Var = parseInt(event.target.value2.value);

            Template.sumForm.totalSum = value1Var + value2Var;

            return Template.sumForm.totalSum;           
        }
    });
} 

但这不起作用。

任何人都可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

您可以使用reactive-var来实现您想要的目标

首先,您必须添加轻量级的反应变量包

meteor add reactive-var

然后在您的模板文件中添加:

if (Meteor.isClient) {
  Template.sumForm.created = function () {
    //We set default value
    this.counter = new ReactiveVar(0);
  }
  Template.sumForm.helpers({
    totalSum: function () {
     return Template.instance().counter.get();
    }
 });
 Template.sumForm.events({
   'submit form': function(event, template){
   event.preventDefault();

   value1Var = parseInt(event.target.value1.value);
   value2Var = parseInt(event.target.value2.value);

   var sum = value1Var + value2Var;
   return template.counter.set(sum);;
  }
 });
}

答案 1 :(得分:0)

Template.sumForm.helpers({
  totalSum: function(){
    return Session.get("sum");
  }    
});

在提交活动结束时

Session.set("sum", value1Var + value2Var);

对于更清洁的解决方案,还可以考虑使用reactive-var而不是会话变量。