鉴于此:
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"];
_.each(names, function (name) {
Players.insert({
name: name,
score: Math.floor(Random.fraction() * 10) * 5
});
});
}
});
}
如何编写模板事件以一次显示一个名称,并单击一个按钮以遍历列表的其余部分?
答案 0 :(得分:0)
如果我理解你的问题,你可以写
@yourTemplate
<template name="yourTemplate">
{{#each players}}
{{name}} - {{score}}
{{/each}}
<button class="add-player">Add Player</button>
</template>
@yourJSFile
//We set default value at Session variable numberOfPlayers
Template.yourTemplate.created = function () {
Session.setDefault("numberOfPlayers",1);
}
//We set a helper which return players at template
Template.yourTemplate.helpers({
players: function () {
return Players.find({}, {limit:Session.get("numberOfPlayers")});
}
});
//When you click at button just add one at Session variable and that triggers the helper to return the next player
Template.yourTemplate.events({
"click .add-player": function (event, template) {
event.preventDefault();
var numOfPlayers = Session.get("numberOfPlayers");
Sessionl.set("numberOfPlayers", numOfPlayers+1);
}
});
答案 1 :(得分:0)
请注意,今晚不是您正在寻找的答案,但遗憾的是meteor还不支持mongoDB的cursor.hasNext()
和cursor.next()
功能。否则,您可以在模板事件代码中执行类似的操作:
var players;
Template.leaderboard.created = function(){
players = null;
}
Template.leaderboard.events({
'click .next': function () {
if(players.hasNext()){
players.next();
}
}
}
它支持cursor.forEach()
方法。你想要详细解决什么?我确定您的用例有一个可行的解决方案,请告诉我们更多详细信息。
答案 2 :(得分:0)
如果您正在迭代的Collection不会更改,或者您不需要处理这些数据更改,则可以执行以下操作:
工作实例 http://meteorpad.com/pad/89r8ZKR8M5fHLCyx5/IterateStaticData
// store some local state here for your iteration
var currentIndex = 0;
var myPlayers;
Template.leaderboard.events({
'click #iterateNames' : function(){
currentIndex++;
// only load the data once
if(!myPlayers){
myPlayers = Players.find({}).fetch();
}
if(currentIndex===myPlayers.length){
currentIndex = 0;
}
var currentPlayer = myPlayers[currentIndex];
Session.set("nextPlayer",currentPlayer);
}
});
如果您正在迭代的Collection确实发生了变化,并且您需要处理这些数据更改,您可以执行以下操作:
工作实例 http://meteorpad.com/pad/3aEjv5HaGPzSDcvKY/IterateDynamicData
var found = []; // people we've found in this iteration loop
function findNext(){
var queryNext = {_id:{$nin:found}};
return Players.findOne(queryNext);
}
Template.leaderboard.events({
'click #iterateNames' : function(){
var nextPlayer = findNext();
if(nextPlayer){
found.push(nextPlayer._id);
}
if(!nextPlayer){
found = [];
nextPlayer = findNext();
found.push(nextPlayer._id);
}
// do something with the next item
someDomElement.innerHTML = nextPlayer.name;
})
虽然meteorpad示例app似乎在迭代时始终显示顺序,但我认为不能保证该顺序。如果有人可以详细说明它会很有趣。