Most apps however are still rendered on the backend initially, especially since it’s advantageous for SEO.
This article describes a technique to link Backbone Views to their server rendered HTML elements and passing additional data into them.
Initializing Views after loading the page
Your page probably consists of different components types with their own DOM structure and styling. If each component has a CSS class and a Backbone View you can connect the two and initialize a View instance for each time the component is used on the page.
This is an example for the type of configuration data that would be required:
Once the pages has finished loading you can bootstrap the views by iterating over all the component types, finding where the component is used on the page, and then creating an instance of the View for every component instance.
Improving this structure
The structure above has one drawback: it uses a centralized list of component types.
To avoid this issue a
registerComponent function that appends the new view type can be added. After each declaration of a Backbone view
registerComponent would be called with the view and DOM element selector.
Passing data into the views
The solution is to include a bit of JSON in the component code that contains the data needed for the View. This is the new DOM for the component:
The code for bootstrapping the views needs to be updated to retrieve the data from the DOM and forward it to the view instance:
Note that the code uses
el.children rather than
el.find - this allows for nested components/views.