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();
});
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);
});
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With