I have a backbone view that calls to a sub-view:
lr.MapView = Backbone.View.extend({
el: $('#map'),
foo: "bar",
initialize: function() {
var that = this;
_.bindAll(this, "render", "addAllEvents", "addOneEvent");
this.collection = new lr.Events();
this.collection.fetch({
success: function(resp) {
that.render();
that.addAllEvents();
}
});
},
addAllEvents: function() {
this.collection.each(this.addOneEvent);
},
addOneEvent: function(e) {
var ev = new lr.EventView({
model: e
});
},
render: function() {
}
});
Here is the sub-view:
lr.EventView = Backbone.View.extend({
initialize: function() {
_.bindAll(this, "render");
console.log(lr.MapView.foo); // will console.log 'undefined'
},
render: function() {
}
});
I’d like to be able to access properties the parent view within the sub-view, but it isn’t working with the above code. For example, how can I access the ‘foo’ variable within the sub-view?
lr.MapViewis a “class”, everything thatBackbone.View.extendbuilds will be inlr.MapView.prototype, not inlr.MapView. Run this with the console open and you’ll see whats going on:Demo: http://jsfiddle.net/ambiguous/DnvR5/
If you’re only going to have a single MapView then you can refer to
lr.MapView.prototype.fooeverywhere:Note that everywhere includes within
lr.MapViewinstances so yourfoowill act like a “class variable” from non-prototype based OO languages.The right way to do this is to use an instance variable for
fooand pass the parent view instance to the sub-view instances when they’re created:Or better, add an accessor method to
MapView:and use that method in
EventView:Proper encapsulation and interfaces are a good idea even in JavaScript.