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 this
outside the for loop.
var that = this;
this
is not transported inside the loop if you use _.each()
.
In Javascript, whenever you enter a new function context, the value of this
has likely changed. All you need to do is store the value of this
before you enter the function:
render: function() {
var self = this;
this.model.somecollection.forEach(function(c) {
var view = new ChildView({ model: c });
self.el.append(view.render().el); //*****
});
return this;
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With