【问题标题】:Why won't my balance change?为什么我的余额不会改变?
【发布时间】:2016-02-26 07:04:41
【问题描述】:

如果函数“neww”为真,我试图让平衡上升,如果为假,则平衡下降。 neww 是一个 0-1 的随机数:

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

所以这应该根据随机生成的数字声明新的 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);
    }
  }
});

如果数字大于 .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
  });
}

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

【问题讨论】:

    标签: javascript html meteor


    【解决方案1】:

    neww 与所有助手一样,仅在您的模板本身中可用。如果你想在你的 JS 中使用它,只要把它变成一个普通的 JS 函数并像平常一样调用它。如果你也想在模板中使用它,你也可以将该函数分配给一个助手。

    目前,neww 在您尝试使用它的上下文中是未定义的,因此当您单击该按钮时,您应该会在控制台中看到错误。该函数会在它真正做任何事情之前抛出,这就是为什么余额没有发生任何事情。

    【讨论】:

      【解决方案2】:
      1. 这不是 if 的正确语法

        如果 (neww = true)

      2. neww 不是变量,它是一个助手,因此你不能像这样在 if 中创建它。为了让newwbalance 模板上可用,您需要将其保存到像Session 这样的全局变量中

      我知道您是编码新手,因此,请先了解基本编程。直接使用像meteor 这样的框架会让你逐渐感到无聊

      【讨论】:

      【解决方案3】:

      您可以通过以下方式修复代码以使其按您的意愿行事:

      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

      【讨论】:

        猜你喜欢
        • 2022-11-28
        • 2020-08-27
        • 2022-07-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-02
        • 2016-02-18
        相关资源
        最近更新 更多