Is there a way to get index while iterating through a collection in Meteor? [duplicate]

痞子三分冷 提交于 2019-11-29 10:43:34

Another solution, in line with maintaining the reactivity of the collection, is to use a template helper with the map cursor function.

Here's an example showing how to return the index when using each with a collection:

index.html:

<template name="print_collection_indices">
  {{#each items}}
    index: {{ this.index }}
  {{/each}}
</template>

index.js:

Items = new Meteor.Collection('items');

Template.print_collection_indices.items = function() {
  var items = Items.find().map(function(doc, index, cursor) {
    var i = _.extend(doc, {index: index});
    return i;
  });
  return items;
};

There's no easy way to do this right now, the latest version of handlebars supports an @index field (which would do what you want), but it's not yet implemented in meteor's version - https://github.com/meteor/meteor/issues/489.

Certainly you could implement your own {{#each_with_index}} helper, it would look something like this:

Handlebars.registerHelper('each_with_index', function(items, options) {
  var out = '';
  for(var i=0, l=items.length; i<l; i++) {
    var key = 'Branch-' + i;
    out = out + Spark.labelBranch(key,function(){ 
      options.fn({data: items[i], index: i});
    });
  }

  return out;
});

The downside of this is you lose the niceness of meteor's {{#each}} helper, which doesn't reactively re-render the whole list when a single item changes.

EDIT: thanks @zorlak for pointer to https://github.com/meteor/meteor/issues/281#issuecomment-13162687

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