I want to my view to render itself when it is first created, so I am calling this.render(); in the initialize: function, like this (some code removed):
var MyView = Backbone.View.extend({
el: $("#mydiv"),
initialize: function() {
this.render();
}
...
In the render: function I’m then looping through a child collection, and appending the rendered views of each child element:
render: function() {
this.model.somecollection.forEach(function(c) {
var view = new ChildView({ model: c });
this.el.append(view.render().el); //*****
});
return this;
},
The problem I’m having is that that the reference to this in the render function (marked with asterisks) is set to window rather than the MyView object, and it’s causing an error.
I assume I am calling render incorrectly (currently this.render(); ). How should I be doing this so that the this context is preserved?
Save
thisoutside the for loop.thisis not transported inside the loop if you use_.each().