Skip to content
FrontDepth, Home

2010 – today

MVC in the browser (Backbone)

Data moves out of the DOM into models that fire change events; views listen to them and re-render their own part of the page.

JuniorMiddleRuns on: Backbone 1.6.1, Underscore 1.13.8, jQuery 4.0.0

The problem

With jQuery the page itself was the data: to find out which todos were done, code read classes off <li> elements, and every handler changed the DOM in its own way. As pages grew into applications that load JSON from a server and stay open for hours, the missing home for the data became a problem: there was nothing to test without a page or to send back to the server, and no rule said which code updates which part of the screen.

The idea

Backbone gives the data objects of its own. A model holds attributes and fires events when set() changes them; a collection is an ordered list of models; a view owns one element, renders it from its model and subscribes to changes with listenTo(). A view's events hash maps DOM events to its methods, delegated to the view's element. A model can save() itself and a collection can fetch() its list, as JSON over a REST API.

Here every todo has a TodoView that redraws its <li> from an _.template when the model changes, and the app view keeps the counter and the filter buttons up to date; even the filter sits in a model. Backbone renders nothing by itself: each view decides what to redraw and when.

What hurt next

Backbone left the wiring to you. Every view subscribed to its models by hand, chose what to redraw and read form fields back itself, so much of the code only connected data to the DOM. A view thrown away without remove() stayed subscribed and kept reacting as a "zombie view", and re-rendering a template replaced elements, losing focus and half-typed text. AngularJS answered with two-way data binding: the HTML declares what shows what, and the framework keeps the page and the data in sync.

Next era: Two-way binding (AngularJS)

How close this is to the original

Runs Backbone 1.6.1 (April 2025) with Underscore 1.13.8 and jQuery 4.0.0 as Backbone.$. Code before 0.9.9 subscribed with collection.bind("add", this.addOne, this), because listenTo arrived only then (bind still works as an alias of on). Until Underscore 1.7.0, _.template(text, data) rendered at once; since then it always returns a function. Templates usually sat in <script type="text/template"> blocks, but the lab removes scripts from index.html, so the item template is a string in the code. Apps created todos with collection.create(), which saved them through Backbone.sync (to a server or, in the Backbone Todos example, a localStorage adapter), and TodoMVC kept the filter in the URL with Backbone.Router. The lab has no server and the demo leaves out the router, so the todos and the filter live only in memory.

The todo app in this era