Alejandro Veintimilla
Alejandro Veintimilla

Reputation: 11523

Backbone.js CollectionView not rendering html

I'm kind of new to Backbone. I'm stuck and I can't find the bug that prevents this code from rendering the html to the #times_day element. The console.log says that the collection's el is an empty div I don't know why:

TheModel = Backbone.Model.extend({
    urlRoot: '/times/api/day_list'
});

DayCollection = Backbone.Collection.extend({
    model: TheModel,
    url: '/times/api/day_list'
})


DayView = Backbone.View.extend({
    tagName: 'li',
    render: function(){
        return '<h3>' + this.model.get('comments') + this.model.get('minutes') + '</h3>'
    }
})

CollectionView = Backbone.View.extend({
    initialize: function(){
        this.collection.on('reset', this.addAll, this);
    },

    addAll: function(){
        this.collection.forEach(this.addOne, this);     
    },

    addOne: function(dayItem){
        var dayView = new DayView({model:dayItem});
        dayView.render()
        this.$el.append(dayView.el);
    },

    render: function(){
        this.addAll();
    }
});


var dCollection = new DayCollection({})
var cView = new CollectionView({collection:dCollection});

dCollection.fetch({
    success: function(){
        cView.render();
        console.log(cView.el);
        $("#times_day").html(cView.el);
    }
})

Maybe it is a simple bug I can't see.. or maybe it is a more important concept I need to learn. Thanks a lot for your help.

Upvotes: 0

Views: 62

Answers (1)

StateLess
StateLess

Reputation: 5402

DayView = Backbone.View.extend({
    tagName: 'li',
    render: function(){
        this.$el.html('<h3>' + this.model.get('comments') + this.model.get('minutes') + '</h3>');
    }
})

instead returning string in render you should set the html to view's el as you are appending el element in collectionView

Upvotes: 3

Related Questions