我有一个由名称和分数组成的排行榜流星示例应用程序:请参阅--> http://leaderboardtry.meteor.com/
我希望元素的顺序在单击切换按钮时在分数和名称之间切换。这是我尝试过的: Javascript:
// Set up a collection to contain player information. On the server,
// it is backed by a MongoDB collection named "players".
Players = new Meteor.Collection("players");
Session.set("sort_by", "score");
if (Meteor.isClient) {
Template.leaderboard.players = function () {
return Players.find({}, {sort: {score: -1}});
};
Template.leaderboard.selected_name = function () {
var player = Players.findOne(Session.get("selected_player"));
return player && player.name;
};
Template.player.selected = function () {
return Session.equals("selected_player", this._id) ? "selected" : '';
};
Template.leaderboard.events({
'click input.inc': function () {
Players.update(Session.get("selected_player"), {$inc: {score: 5}});
},
'click input.toggle': function(){
var switch_sort = Session.equals("sort_by", "name")?"score":"name";
Session.set("sort_by", switch_sort);
var togg = Session.get("sort_by");
if (togg == "score"){
Players.find({}, {sort: {score: -1}});
} else {
Players.find({}, {sort: {name: -1}});
}
}
});
Template.player.events({
'click': function () {
Session.set("selected_player", this._id);
}
});
}
// On server startup, create some players if the database is empty.
if (Meteor.isServer) {
Meteor.startup(function () {
if (Players.find().count() === 0) {
var names = ["Ada Lovelace",
"Grace Hopper",
"Marie Curie",
"Carl Friedrich Gauss",
"Nikola Tesla",
"Claude Shannon"];
for (var i = 0; i < names.length; i++)
Players.insert({name: names[i], score: Math.floor(Math.random()*10)*5});
}
});
}
HTML
<head>
<title>Leaderboard</title>
</head>
<body>
<div id="outer">
{{> leaderboard}}
</div>
</body>
<template name="leaderboard">
<input type="button" class="toggle" value="toggle sort" />
<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" />
</div>
{{/if}}
{{#unless selected_name}}
<div class="none">Click a player to select</div>
{{/unless}}
</template>
<template name="player">
<div class="player {{selected}}">
<span class="name">{{name}}</span>
<span class="score">{{score}}</span>
</div>
</template>
问题肯定是我在 JS 中的尝试。感谢您的帮助,因为我是流星/蒙戈的新手
谢谢!