Meteor filter for each

送分小仙女□ 提交于 2019-12-25 03:57:13

问题


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, or fetch methods can only be called once on a cursor. To access the data in a cursor more than once, use rewind 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!