【问题标题】:Balance is still stuck at 5000余额仍停留在5000
【发布时间】:2016-02-27 13:44:10
【问题描述】:

我已经尝试了我能想到的一切,我的平衡无论如何都不会改变。我目前的代码是:

if (Meteor.isClient) {
  Session.setDefault('num', Random.fraction());
  Session.setDefault('bal', 5000)

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

  Template.Balance.helpers({
    bal: function () {
      return Session.get('bal');
    }
  });

  Template.hello.events({
    'click button': function () {
      Session.set("num", Random.fraction());
    }
  });

   Template.TrueFalse.helpers({
  'trueFalse': function(){
    return( Session.get('num') > 0.5 ? true : false )
  }
});

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

}
if (Meteor.isServer) {
  Meteor.startup(function () {
  });
}

我尝试了一些以前的解决方案,但似乎都没有。

我认为这可能与生成随机数的事实有关,并检查它是否同时大于或小于 0.5,因为这两个功能都是“点击按钮”,但我不会不知道怎么解决。

有人可以编写修复代码,我会弄清楚你做了什么?

谢谢。

顺便说一句,如果有帮助,这是 HTML 文件:

<head>
  <title>RNG</title>
</head>

<body>
  <h1>{{> Balance}}</h1>

  {{> hello}}

  <h1>{{> TrueFalse}}</h1>
</body>

<template name="hello">
  <button>Click Me</button>
  <p>You've pressed the button {{num}} times.</p>
</template>

<template name="TrueFalse">
    {{#if trueFalse}}
        You Win!
    {{else}}
        You Lose!
    {{/if}}
</template>

<template name="Balance">
    Balance: {{bal}}
</template>

【问题讨论】:

    标签: javascript html meteor


    【解决方案1】:

    我没有真正使用过 Meteor,但它看起来是这样的:当您为模板定义事件时,事件选择器仅匹配 within 模板。所以在 Balance 模板中绑定的 click button 事件永远不会被触发,因为 Balance 模板中没有按钮。

    您可以在 Hello 模板的 click button 事件中更新余额:

      Template.hello.events({
        'click button': function () {
          Session.set("num", Random.fraction());
          if ( Session.get('num') > 0.5 ) {
            Session.set('bal', Session.get('bal') + 1);
          } else {
            Session.set('bal', Session.get('bal') - 1);
          }
        }
      });
    

    【讨论】:

    • 您确实需要更新 hello 模板中的余额,但它不起作用。我不确定为什么。有没有办法,而不是在单击按钮时运行它,而是在不久之后运行它?
    • 忽略我刚才所说的所有内容:P 解决方案有效。太感谢了。我没有说谎,我已经尝试了 3 天来解决这个问题。
    猜你喜欢
    • 2018-06-15
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 1970-01-01
    • 2017-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多