Collection.each () does not iterate over models

I am trying to iterate over models retrieved using a collection.

I have the following code:

initialize: function() { this.collection = new UserCollection(); this.collection.fetch(); this.render(); }, renderCollection: function() { console.log("rendering collection"); this.collection.each(function(index,model){ console.log("model"); }); console.log(this.collection); }, render: function() { this.template = _.template(template, {}); this.$el.html(this.template); // some other stuff this.renderCollection(); } 

and results:

 rendering collection d {models: Array[0], length: 0, _byId: Object, constructor: function, model: function…} _byId: Object _idAttr: "id" length: 4 models: Array[4] 0: d _changing: false _events: Object _pending: false _previousAttributes: Object attributes: Object created: "2013-02-13 09:22:42" id: "1" modified: "2013-02-13 09:22:42" role: "admin" username: " email@gmail.com " __proto__: Object changed: Object cid: "c5" collection: d id: "1" __proto__: e 1: d 2: d 3: d length: 4 __proto__: Array[0] __proto__: e user_list.js:25 

So the sampling method really worked - in the dump of the object I can find 4 records, but the collection iteration does not work ...

+7
source share
2 answers

Based on the result you provided, it does not look as if any “model” was printed. This is probably due to the fact that when the .each() block is .each() , this.collection may not have been fully selected yet. This is due to the asynchronous nature of JavaScript.

Try this in your initialization method:

 initialize: function() { var me = this; this.collection = new UserCollection(); // Listen to 'reset' events from collection, so when .fetch() is completed and all // ready to go, it'll trigger .render() automatically. this.listenTo(this.collection, 'reset', this.render); this.collection.fetch(); }, 

Another way to handle this is to add a success handler on extraction, but I think that when listening for events, reset should be enough.

Hope this helps!

By the way, as Cyclone says, the handler for .each should just be a model without an index. :)

+8
source

Running each in the collection gives model itself as an argument .

Try the following:

 this.collection.each(function(model){ console.log(model); }); 

It should give you a model for the current iteration.

+19
source

All Articles