Implement Inheritance in BackboneJS |
Here is an simple Backbone view:
//viewParent.js
define(function (require) {
return Backbone.View.extend({
el: $("#parent"),
initialize: function (opts) {
console.log("Parent view initialized.");
},
events: {
"click .dad" : "buttonHandler"
},
render: function () {
var html = "<button class='btn dad'>I am Dad</button>";
$(this.el).html(html);
},
buttonHandler: function() {
$(this.el).append("<div class='message'>I exist in Parent</div>");
}
});
});
This view just adds a button to the page. This button has a handler which adds some HTML to our page. Nothing special happens here. No suppose we have one more view which performs similar kind of functionality. So we will create second view which will inherit the ‘viewParent’ view class.
//viewChild.js
define(function (require) {
//Include the parent view
var parentView = require("views/viewParent");
//Inherit the parent view
return parentView.extend({
el: $("#child"),
initialize: function(opts) {
//Call the parent's initialize method
parentView.prototype.initialize.apply(this, [opts]);
console.log("Child view initialized.");
},
events: {
"click .child" : "buttonHandler" //This function does not exist in this inherited view
},
render: function () {
var html = "<button class='btn child'>I am Son</button>";
$(this.el).html(html);
},
});
});
As you can see that we have required the ‘viewParent’ class and extended that using .extend() method of underscore. Now this child view will have all the features of the parent class. You can see that the click handler function ‘.buttonHandler’ does not exist in child class, still it has been used in it. If the method is not found in the child class, it will be searched up in the parent class thus leading to inheritance.