问题
i have a problem with filter and each. i want create a filter, that will change data according to that filter.
<select id="filter">
<option value="all">all</option>
<option value="one">one</option>
<option value="two">two</option>
</select>
{{#each datas}}
<span class="badge">{{Name}}</span>
{{/each}}
Template.mytemp.created = function(){
Session.set("activefilter", "all");
};
Template.mytemp.datas = function(){
var ac = Session.get("activefilter");
var result = new Array();
if(ac != undefined){
var data = RawData.find({filter:ac}).fetch();
for(var ii = 0; ii < data.length;ii++){
var nData = NextData.findOne({_id : data[ii].Next_ID});
result[ii] = {
Name : nData.Name
};
}
return result;
}
};
i create an event handler like this :
Template.mytemp.events({
'change #filter':function(){
Session.set("activefilter",$('#filter').val());
}
});
everytime i change the filter, nothing happend, datas on each not changed. please help me how to update datas when filter change?
回答1:
When you manually iterate over a cursor (with each
etc) you will have to rewind your cursor to reset it. Taken from the docs http://docs.meteor.com/#rewind
The
forEach
,map
, orfetch
methods can only be called once on a cursor. To access the data in a cursor more than once, userewind
to reset the cursor.
Therefore you can do something like this:
Template.mytemp.datas = function(){
var ac = Session.get("activefilter");
var result = new Array();
if(ac != undefined){
var cursor = RawData.find({filter:ac});
var data = cursor.fetch();
for(var ii = 0; ii < data.length;ii++){
var nData = NextData.findOne({_id : data[ii].Next_ID});
result[ii] = {
Name : nData.Name
};
}
cursor.rewind(); //we rewind our cursor here so that it can be iterated again from the beginning when needed
return result;
}
};
来源:https://stackoverflow.com/questions/21886932/meteor-filter-for-each