0

With Backbone.js, I'm trying to bootstrap my data into a collection. My bootstrap looks like log.reset( <JSON> );

When I console.log my collection I see a bunch of objects full of data. The problem is when I console.log on the individual models in the loop, I see a bunch of empty objects with no data. The data is all there in the collection, but I can't get it to pass into my template on each forEach pass. I used the exact same code structure on another part of my project to render a collection view which works perfectly... I don't know why this one isn't working.

Note that I am listening for the reset event on the collection.

//Log Model
var LogItem = Backbone.Model.extend({});

var logItem = new LogItem();


//Log Collection
var Log = Backbone.Collection.extend({
    model: LogItem
});

var log = new Log();


//Log Item View
var LogItemView = Backbone.View.extend({
    tagName: 'tr',
    template: _.template($('#log-item-template').html()),
    render: function(){
        var attributes = this.model.toJSON();
        this.$el.html(this.template( attributes ));
        console.log( this.model.toJSON() ); //This shows a bunch of empty objects
        return this;
    }
});


//Log View
var LogView = Backbone.View.extend({
    el: '#log',
    initialize: function() {
        this.collection.on('reset', this.render, this);
    },
    render: function(){
        this.addAll();
        console.log( this.collection.toJSON() ); //This shows objects full of data
    },
    addOne: function(food) {
        var logItemView = new LogItemView({model: logItem});
        this.$el.append(logItemView.render().el);
    },
    addAll: function() {
        this.$el.html('');
        this.collection.forEach(this.addOne, this);
    }
});

var logView = new LogView({collection: log});

How can I fix my empty models?

eablokker
  • 103
  • 1
  • 5

1 Answers1

1

While building your subviews, your addOne method declares a food argument but you call your LogItemView constructor with {model: logItem}

Try

addOne: function(food) {
    var logItemView = new LogItemView({model: food});
    this.$el.append(logItemView.render().el);
}
nikoshr
  • 32,926
  • 33
  • 91
  • 105