为什么我的余额不会改变?

时间:2016-02-25 21:36:37

标签: javascript html meteor

如果函数“neww”为true,我试图保持平衡,如果为false则向下。 neww是0-1的随机数:

 Template.result.helpers({
  'neww': function(){
    return( Session.get('number') > 0.5 ? true : false )
  }
});

所以这应该根据随机生成的数字声明新的真或假吗?好吧,我有一个像这样的if else声明:

Template.balance.events({
  'click button': function() {
    if (neww = true) {
      Session.set('bal', Session.get('bal') + 1);
    } else {
      Session.set('bal', Session.get('bal') - 1);
    }
  }
});

如果数字大于0.5,它应该提高我的余额1,否则它会降低。

我的整个代码是:

if (Meteor.isClient) {
  // counter starts at 0
  Session.setDefault('number', Random.fraction());
  Session.setDefault('word', "");
  Session.setDefault('bal', 5000);


  Template.hello.helpers({
    number: function () {
      return Session.get('number');
    }
  });

    Template.balance.helpers({
    bal: function () {
      return Session.get('bal');
    }
 });
  Template.hello.helpers({
  word: function () {
    return Session.get('word');
  }
});

  Template.hello.events({
    'click button': function () {
      // increment the counter when button is clicked
      Session.set("number", 0+Random.fraction());
    }

  });

 Template.result.helpers({
  'neww': function(){
    return( Session.get('number') > 0.5 ? true : false )
  }
});

Template.balance.events({
  'click button': function() {
    if (neww = true) {
      Session.set('bal', Session.get('bal') + 1);
    } else {
      Session.set('bal', Session.get('bal') - 1);
    }
  }
});

}

if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
  });
}

任何帮助或提示都将不胜感激。

3 个答案:

答案 0 :(得分:0)

像所有帮助者一样,

neww仅在您的模板中可用。如果你想在你的JS中使用它,只需使它成为一个普通的JS函数并正常调用它。如果您也想在模板中使用它,也可以将该函数分配给帮助程序。

目前,{I}将在您尝试使用它的上下文中未定义,因此当您单击按钮时,您应该会在控制台中看到错误。该函数会在它实际执行任何操作之前抛出,这就是为什么没有任何事情发生在平衡点上。

答案 1 :(得分:0)

  1. 这不是if

    的正确语法

    if(neww = true)

  2. neww不是变量,它是一个助手,因此你不能在if那样做。为了让neww模板上的balance可用,您需要将其保存为全局变量,例如Session

  3. 我知道您不熟悉编码,因此,首先要了解基本编程。立即使用像meteor这样的框架会让你感到无聊

答案 2 :(得分:0)

以下是如何修复代码以使其按照您的意愿执行操作的方法:

Template.balance.events({
  'click button': function() {
    if ( Session.get('number') > 0.5 ) {
      Session.set('bal', Session.get('bal') + 1);
    } else {
      Session.set('bal', Session.get('bal') - 1);
    }
  }
});

你可以完全摆脱你的neww助手。要了解有关模板助手,事件和会话如何工作的更多信息,请查看Meteor Guide

相关问题