I have a Backbone view (see below) that I believe to be doing the right thing
Index = Backbone.View.extend({
render: function() {
var activities = new Activities();
activities.fetch();
var tpl = Handlebars.compile($("#activities-template").html());
$(this.el).html(tpl({activities: activities.toJSON()}));
return this;
}
});
If execute each line in the render() function with Chrome JS console I get the expected result with the element I pass in getting populated with the template output. However, when I run this using the following
var i = new Index({el: $("body")})
i.render()
“i.$el” is completely empty–the HTML is not getting rendered like it does in console. Any ideas why?
fetchis an AJAX call so there’s no guarantee thatactivities.toJSON()will give you any data when you do this:Executing the code in the console probably gives the AJAX call time to return with something before you try to use
activities.You should do two things:
activitiesis empty.Attach your view’s
renderto the collection’s"reset"event:I also switched to
this.$el, there’s no need to$(this.el)when Backbone already gives youthis.$el.