Backbone View doesn't fire the render method

I can’t understand why the render method doesn’t fired ? but if i put in the console categoriesView.render() , everything works.

var Category = Backbone.Model.extend();
var Categories = Backbone.Collection.extend({
url: '/data.json',
initialize: function(){
	this.fetch();
},
model: Category
});

var CategoryView = Backbone.View.extend({
tagName: 'li',
template: _.template($('.template').html()),
render: function(){
	this.$el.html(this.template(this.model.toJSON()));
	return this;
}
});

var CategoriesView = Backbone.View.extend({
tagName: 'ul',
initialize: function() {
	this.render();
},
render: function(){
	this.collection.each(function(data){
		var categoryView = new CategoryView({model: data});
		this.$el.append(categoryView.render().el);
	}, this);

	return this;
}
});

var category = new Category();
var categories = new Categories();
var categoriesView = new CategoriesView({collection: categories});

categoriesView.render();

$('body').append(categoriesView.el);

Hi Salmen,

I suspect it’s because even though you’re calling fetch on the collection as soon as it’s initialized, the data doesn’t load until after you’ve appended categoriesView to the page, so it doesn’t have anything to render.

Try listening for the collection’s sync event within the view, to trigger the render method:

var CategoriesView = Backbone.View.extend({
    tagName: 'ul',
    initialize: function() {
        this.collection.on('sync', function(){
            this.render();
        }, this);
    },
    // ...
});

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.