backbone.js iterate a collection
25,556
Fetch is asynchronous. Rewrite your code to call render with a callback:
var LogListView = Backbone.View.extend({
el: $('#logs-list'),
initialize: function() {
var self = this;
this.collection = new LogList();
this.collection.fetch().done(function(){
self.render();
});
},
render: function() {
this.collection.each(function(log) {
console.log('log item.', log);
});
}
});
Author by
porterhaus
Updated on May 14, 2020Comments
-
porterhaus almost 4 years
I have set up a collection for Logs. The api returns the results as JSON. I saw a previous topic where it was suggested to add the parse method on the collection. Having done so, when I execute the code I am not getting any output to the console. Nevertheless, I am new to Backbone so any insight and/or guidance would be appreciated. My understanding of collection.each may not be correct.
var Log = Backbone.Model.extend({}); var LogList = Backbone.Collection.extend({ model: Log, url: 'api/logs', parse: function(response) { return response.logs; } }); var LogListView = Backbone.View.extend({ el: $('#logs-list'), initialize: function() { this.collection = new LogList(); this.collection.fetch(); this.render(); }, render: function() { this.collection.each(function(log) { console.log('log item.', log); }); } }); $(document).ready(function(){ console.log('ready.'); new LogListView(); });