【问题标题】:What is wrong with my meteor leaderboard example?我的流星排行榜示例有什么问题?
【发布时间】:2014-08-01 19:45:19
【问题描述】:

我刚刚安装了 Meteor,正在查看排行榜示例。

我正在尝试设置随机分数,但看不出我的代码有什么问题。谁能看到这有什么问题?我希望当单击按钮时,所选玩家的分数会填充随机数。

模板代码:

<template name="leaderboard">
<div class="leaderboard">
{{#each players}}
  {{> player}}
{{/each}}
</div>

{{#if selected_name}}
<div class="details">
<div class="name">{{selected_name}}</div>
 <input type="button" class="inc" value="Give 5 points" />
 <input type="button" class="incrandom" value="Set random points" />
</div>
{{else}}
<div class="none">Click a player to select</div>
{{/if}}
</template>

JS代码:

  Template.leaderboard.events({
    'click input.incrandom': function () {
    Players.update(session.get("selected_player"), {$incrandom: {score: Math.floor(Random.fraction()*10)*5 }});
    }
  });

【问题讨论】:

  • 第一:把session改成Session

标签: meteor


【解决方案1】:

MongoDB 中没有$incrandom 运算符,只有$inc

另外,这段代码 sn-p 中的Random 是什么?您可能打算使用Math.random()

另外(谢谢@apendua,我没注意到),session 应该是Session

所以更新后的代码是:

Template.leaderboard.events({
    'click input.incrandom': function () {
    Players.update(Session.get("selected_player"), {$inc: {score: Math.floor(Math.random()*10)*5 }});
    }
  });

但是请注意,这不会设置玩家的分数为随机值,而是增加玩家的分数随机值。

要设置玩家的分数,请改用$set 运算符。

【讨论】:

  • 太好了,谢谢您的回复。我确实打算使用 Random.fraction,因为这就是示例的服务器部分中的内容。我认为 $inc 以某种方式指代该类,以前也从未使用过 Mongo。对我来说是全新的,非常感谢您在这方面的帮助!
  • 不客气。你使用Random 是对的,我不知道Meteor 附带的random 包。
猜你喜欢
  • 2014-04-21
  • 1970-01-01
  • 2014-09-26
  • 1970-01-01
  • 2015-11-22
  • 2021-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多