Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbone.js iterate a collection

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();
});
like image 424
porterhaus Avatar asked May 14 '13 00:05

porterhaus


1 Answers

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);
    });
}
}); 
like image 199
Scott Puleo Avatar answered Sep 30 '22 18:09

Scott Puleo