Search code examples
backbone.jsbackbone-viewsbackbone-routing

How to organize groups of views that are common across pages?


Suppose that you have a group of backbone views that combine on the page to create one pretty complex widget that's going to appear on multiple pages. (An example of this might be a form where each input is its own view and perhaps has complex behavior of its own.) However, due to a/b testing, the widget might not be exactly the same on each page, some of the internal views may be different... but across the MAJORITY of pages they will all be the same.

We are planning to have a backbone controller for each page. We want to reduce the copy/paste that would come from duplicating the instantiation of all the views that are required for the widget on every page, but we also want the flexibility of being able to swap out an individual view on a particular page for an a/b test.

One of the proposals so far is to create "meta" views (represent the entire form) that instantiate all of the sub-views (form elements), and you could construct the meta-view with alternative sub-views if you needed to. However, that introduces a strange view-hierarchy and also potentially some coupling between the views within the meta-view.

How do people typically approach this problem?


Solution

  • I'd be interested to hear why you think your proposal will result in a strange view hierarchy. To me, the idea of a meta view composed of its various subviews seems to make perfect sense.

    As for the coupling of views, you can mitigate this by ensuring communication is handled via events resulting from changes to shared models and collections, or events triggered via an event aggregator.

    I would definitely have a look at Marionette which is (straight from the docs) a composite application library for Backbone.js that aims to simplify the construction of large scale JavaScript applications. It includes an event aggregator as well as some nifty constructs for creating complex views.

    You might find the layout and region functionality interesting as I imagine you could use it to define the exact configuration of your meta view from each page controller.