Inheriting Views in BackboneJS

BackboneJS provides an awesome technique for structuring our application code. And RequiresJS makes it modular. So we can write separate modules for each HTML block on our page. But sometimes separate views in our application have similar kind of functionalities. Most of the functions in both views are common. So it is not at all recommended to write that common code in both of the Backbone views. It will make application difficult to maintain. To avoid this we can implement a simple OOP technique known as ‘Inheritance’. We can inherit one of the view in other view. So the child view will have all the functionalities of the parent view. Additionally we can add our own methods in the child view or we can override the parent methods in child view by creating methods with same name.

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.

Written by Arvind Bhardwaj

Arvind is a certified Magento 2 expert with more than 10 years of industry-wide experience.

Website: http://www.webspeaks.in/