At Requestly, we are using BackboneJs and we have done a lot of customisations on the top of Backbone framework. One such customisation is how to create a common component i.e Backbone component which is accessible on all the views. One such example of a component is login dialog/component.
Suppose you have a app which has multiple routes and a component hierarchy with each route. This is what we have in Requestly and we want to add login dialog/component to all the top-level views so that it can be triggered from many places.
In order to design this, we have created the following view/model/collection hierarchy.
- BaseModel extends Backbone.Model
- BaseIndexView extends BaseView extends Backbone.View
- BaseModel extends BaseView extends Backbone.View
- BaseModelView is a model based component
- BaseIndexView is a collection based component
Inside BaseView we have defined a field called
includeComponents which contains a list of common components. Concrete classes must override this and define which common component they need and vice versa.
Including Common Component
Next, you have to include the component in your individual views
includeComponentsin individual view and select the component and set the component to true to include it
- Include the template if required as partial
- Add/Implement listeners if the common component sends some events
That’s all you need to include a common component defined in BaseView.
In this section we will describe how you can implement a common component. Here are the steps :-
- Create the component (Model/Collection, View, Template)
- Include the corresponding files in `jsList.json`
- Register the component in includeComponents
- Initialize the component in
- Define any events and event handlers required for this component as if required.
Checkout existing implementation of
needHelpModal in BaseView.js for more understanding.