Source: Thinkerous Blog

Thinkerous Blog Goal: We want our Backbonejs views to synchronize with a single...

Goal:We want our Backbonejs views to synchronize with a single source of truth.As a Backbone app increases in size, keeping state consistent across the components becomes much more difficult. In the post I'll walk through how we avoided this issue with what we call "view models".Background:Initially we used Backbone.Wreqr, a part of MarionetteJS as a way to handle global events. We had nested subviews trigger events with Wreqr.vent, and listened to them from several places to update views. We also used Component/Component to organize code into modules, making it difficult to make direct references to other objects in order to "listenTo()" them.After a few code refactors, we had multiple controllers all extending from the same base controller containing common functionality. We then needed namespaces for each controller to prevent controllers from responding to one another's events. Namespacing quickly became messy because deeply nested subviews need namespace information passed to them through several.We had unintentionally taken local events, made them part of a global event space, and then added tons of code to make them local again. Coding with these events quickly became a nightmare: we started having to search through files just to remember how each event was used. Solution:We eventually went back to basics and used a simple Backbone.Model to track data and trigger events whenever updates occur. We maintained a global model and used it to store state in what we call "View Models". With this in place, any part of the app could simply update the global View Model and everything else can listenTo() it to receive an event saying what has changed.Here is an example of one of our View Models:Backbone.Model.extend({ defaults: { id : null, title : "", edit : false, type : "project" } });For example, we have two modules that need to be synchronized in our app: Sidebar (on the left) and Main (on the right). When a user selects a project in the Sidebar, we want that "active" project updated and shown in the Main. We set up a view model specifically to keep track of which project id is currently active and have the controller update the views as the id is updated by the sidebar.By shifting to View Models we now have centralized sources of state information and have all together removed global events. Overall View Models make the codebase much easier to maintain and far more structured than managing global events with namespacing.

Read full article »
Est. Annual Revenue
$100K-5.0M
Est. Employees
1-25
CEO Avatar

CEO

Update CEO

CEO Approval Rating

- -/100