Backbone extending views
by justinwyllie
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone.js"></script>
JavaScript
//http://www.erichynds.com/blog/backbone-and-inheritance
var SidebarView = Backbone.View.extend();
var MenuView = Backbone.View.extend();
var BaseView = Backbone.View.extend({
// Create a property where we can hold references to subviews
subviews: {}
});
var ContentView = BaseView.extend({
initialize: function() {
this.subviews.sidebar = new SidebarView();
}
});
var HeaderView = BaseView.extend({
initialize: function() {
this.subviews.menu = new MenuView();
}
});
var content = new ContentView();
var header = new HeaderView();
//this shows that given the above code subviews is inherited by both HeaderView and ContentView - as the 'same thing'. It is the
//property of the prototype which they share. The prototype is an instantiated object. "same thing". This is the weakness
//of JavaScript's inheritance.
console.log(content.subviews);
console.log(header.subviews);
//solutions. one solution is to give each class their own instance of subviews e.g.
//but if we do this then what is the point of the inheritance anyway? the whole idea was to create
//a parent class which encapsulates the concept of subviews.
var BaseView = Backbone.View.extend();
var ContentView = BaseView.extend({
subviews: {},
initialize: function() {
this.subviews.sidebar = new SidebarView()
}
});
var HeaderView = BaseView.extend({
subviews: {},
initialize: function() {
this.subviews.menu = new MenuView();
}
});
//this is the post author's solution:
//it works because this.subviews is created for each extend of BaseView and this is separate
//not part of the sharec prototype, for each class which extends BaseView
//he has overriden the prototype.constructor method of BaseView
//but while this works it seems a bit 'unnatural'
//all in all maybe it is not worth trying to create your own views which extend others?
//how does Marionette do it?
var BaseView = Backbone.View.extend({
constructor: function() {
// Define the subviews object off of the...