Key Takeaways
Replace callback tangles with explicit models, views, collections, and events.
Client code grows teeth. A page that fetches data, changes the DOM, and handles user input through scattered jQuery callbacks can become hard to extend. Each new feature adds more places where the interface, business rules, and server data must stay in sync. Backbone offers structure for that complexity without requiring a large framework or a custom architecture built from scratch.
Use structure where it pays. The book’s recurring example is a todo app: users add, edit, complete, filter, and delete items without reloading the page. Those actions make the app rich enough to benefit from explicit components. For a mostly server-rendered site with only a few interactive touches, the same machinery may be unnecessary.
The strongest case for Backbone is not that every browser interaction needs a framework. It is that complexity should become visible before it becomes entangled. Naming the data, interface, and coordination layers gives teams a shared map for debugging and review. This resembles modular design in other engineering fields: boundaries make change easier to localize. The counterweight is real, though. Abstraction also has a cost, and a small interaction can become less clear when wrapped in framework conventions it does not need.
Use Backbone as a flexible MV toolkit, not textbook MVC.
The label is approximate. Classical Model-View-Controller separates domain data, presentation, and a controller that interprets user input. Backbone supplies models, views, collections, and routers, but it does not provide a distinct Controller class. View event handlers often take on controller duties, while routers map URLs to application behavior. The book therefore treats Backbone as an MV design, a model-view architecture with a framework-specific division of responsibilities.
Know the actual boundaries. In a todo view, a click handler can update a model, and the model can announce its change so the interface responds. This differs from a strict classical MVC arrangement, but still separates data from presentation and helps identify what to test.
What's useful here is the distinction between a pattern's purpose and its label. MVC is not a universal blueprint whose parts appear identically in every framework. Treating the name as a guarantee can lead developers to search for a controller that does not exist or to force logic into the wrong layer. The book's caution is broadly applicable: describe the responsibilities a codebase actually has, then judge whether they are sufficiently separated. Architectural vocabulary clarifies only when it matches implementation.
Keep data in models, lists in collections, and rendering in views.
Give each piece a job. A Backbone model holds an entity’s attributes and related behavior. Its `set()` method updates values and emits change events, while `validate()` can reject invalid state. A collection groups models, supports operations such as filtering and sorting, and relays useful events when its members change. A view owns presentation behavior, usually rendering model data through a template into a DOM element.
Follow a change through. In the todo example, a checkbox calls a model method that toggles completion and saves the new value. The model emits a change notification, the corresponding view redraws, and the collection or application view can refresh counts. Templates keep markup separate from the JavaScript that supplies data.
This division creates a practical form of separation of concerns, but it is not a demand for one class per field or one view per visual fragment. The design is valuable when it makes change propagation understandable: a user action changes state, and the interface derives from that state. That is close to the logic behind unidirectional data flow, even though Backbone does not enforce such a system. Teams still need to decide which component owns a rule, especially when a view begins accumulating business decisions.
Treat event subscriptions as lifecycle resources, not harmless callbacks.
Events loosen dependencies. Instead of one component directly calling another, Backbone’s event system lets objects publish and observe named changes. A view can listen for a model’s change event and rerender without the model knowing how the view works. Collections can surface changes from their models, and custom events can connect otherwise separate parts of an app.
Remember to disconnect. A model that outlives a view can retain a callback pointing to that view, keeping the view in memory and causing it to respond after it should be gone. Backbone’s `listenTo()` records subscriptions on the listener, so `stopListening()` can remove them together. The default view removal process cleans up subscriptions made this way.
This is a software version of resource ownership: opening a file, registering a listener, or allocating a view creates an obligation to release it. The event model is powerful precisely because it hides direct call chains, but that flexibility can also hide dependencies and make execution harder to trace. A useful discipline is to treat subscriptions as part of an object's lifecycle, not incidental setup. Explicit cleanup and event naming preserve the benefits of decoupling without leaving invisible connections behind.
Let Backbone.sync translate model operations into a clear server contract.
Persistence follows model intent. Backbone’s `fetch()`, `save()`, and `destroy()` methods delegate to `Backbone.sync`, which maps reads, creates, updates, partial updates, and deletes to HTTP requests. A new model is commonly sent with POST; an existing model is updated with PUT, or PATCH when only changed attributes should be sent; deletion uses DELETE. Collections can fetch a set of models from their URL.
Match the API precisely. The book’s library exercise connects a browser app to a REST API backed by MongoDB. It exposes how mismatched identifiers can break persistence: Backbone expects an `id` by default, while MongoDB returns ` id`. Setting `idAttribute` or translating the response in `parse()` lets Backbone recognize saved records correctly.
The sync layer is an adapter boundary: application code can express an operation on a model while the synchronization implementation handles transport details. That boundary helps isolate server changes and can support alternatives such as browser storage. But a convention is not a substitute for an API agreement. Identifier formats, date representation, validation, and error handling remain contract decisions. The library can streamline the exchange, but it cannot make two systems agree on what their data means.
Add Marionette when view lifecycle and rendering boilerplate overwhelm clarity.
Extend only when needed. Backbone intentionally leaves many application decisions to developers. Marionette adds reusable view types, automatic template rendering, regions for displaying views, and cleanup behavior. Its `ItemView` can replace repeated template-compilation and render code. A `Region` manages a particular place in the DOM: it renders the incoming view and closes the current one when another is shown.
Compose complex screens. Marionette’s `CompositeView` can display a collection and its individual items, including recursive hierarchies. The book refactors the todo app with regions, layouts, and controller-like workflow coordination. Its point is not that every project needs the extension, but that teams can adopt selected components rather than making an all-or-nothing switch.
Extensions are most effective when they encode a repeated solution the team already understands. Marionette's lifecycle management is especially useful because view leaks and repetitive rendering are operational problems, not merely style preferences. Still, a richer framework introduces more concepts and conventions for maintainers to learn. The decision should be based on the frequency and cost of the problem being solved. Abstraction pays when it removes repetition while making the lifecycle easier to see, not when it merely makes files shorter.
Declare module dependencies instead of relying on script-tag order.
Make dependencies explicit. AMD, or Asynchronous Module Definition, lets each JavaScript module declare what it needs and what it provides. RequireJS loads those dependencies, avoiding a fragile chain of script tags whose order must be maintained by hand. Asynchronous loading can keep the browser from waiting on every script before continuing to render, and modules can be loaded only when needed.
Separate development from delivery. The book shows Backbone models, collections, views, and templates wrapped as modules. RequireJS shims help load libraries such as Backbone that do not define AMD modules themselves. The `r.js` optimizer can combine and minify production assets while preserving modules that need to load dynamically. Boilerplate tools can scaffold common files and build steps.
Explicit dependencies improve more than page loading. They make a module's assumptions inspectable, which helps testing, reuse, and refactoring. This is a form of dependency inversion: a component receives what it needs rather than reaching into an unpredictable global environment. Asynchronous loading is not automatically faster in every scenario, since extra requests and loader overhead can offset the benefit. The important distinction is between a clean dependency model during development and an optimized delivery plan for production.
Test behavior with isolated fixtures, spies, and fake responses.
Test the smallest useful unit. Jasmine and QUnit let developers check model defaults, validation, collection behavior, view rendering, and application interactions. Both frameworks support setup and cleanup so tests begin from known conditions. DOM fixtures provide controlled markup for view tests, while assertions check that output and state match expectations.
Control external behavior. A real server makes tests slower and less predictable. Jasmine spies and SinonJS spies can record calls; stubs replace behavior; mocks add expectations about how a dependency should be used. These tools let a test verify, for example, that an Ajax request targets the expected URL and invokes the right callback without contacting a live service.
The central gain is feedback quality. A test that isolates a model rule can identify a regression faster than manually inspecting an entire application. Fakes also make rare server responses reproducible. Yet test counts are not a proxy for correctness: a suite can reliably confirm an incomplete or mistaken specification. The book's test-driven approach addresses this by writing expectations before implementation, while its examples also show why tests must target meaningful behavior rather than merely framework mechanics.
Separate Backbone routing from jQuery Mobile's page enhancement cycle.
Avoid competing navigators. Backbone routes URLs and application states; jQuery Mobile intercepts links, requests pages, and enhances markup into widgets. If both frameworks control navigation, their event and history behavior can conflict. The book’s integration disables jQuery Mobile’s automatic routing and enhancement, lets Backbone choose the page, then calls jQuery Mobile’s page API to enhance and display it.
Enhance dynamic markup deliberately. Newly inserted mobile content may need an explicit page or widget enhancement call. Rebuilding an entire page is simple, while updating a single component can be faster but requires the correct widget-specific refresh method. The book also warns that transitions can consume a large share of load time on some devices, making profiling and device-aware choices important.
This integration illustrates a general principle of composition: two libraries can coexist when each has a clearly bounded responsibility. The challenge is that a user-visible page transition is not one operation. Routing, DOM insertion, widget initialization, history, and animation each have separate timing and state. Treating them as one event invites subtle bugs. The tradeoff is complexity: custom coordination offers control, but it also means developers must understand both frameworks' lifecycles rather than relying on either one alone.
Choose server paging or client paging based on where data lives.
Pagination has two locations. Backbone.Paginator distinguishes `requestPager`, which asks a server for a particular page, from `clientPager`, which divides a dataset already loaded into the browser. Request paging limits each network response and suits APIs that provide paginated results. Client paging avoids another request when users move between pages, but requires the relevant dataset to be available locally.
Let context decide. A search API with thousands of matches may return a small subset per request, with sorting and query parameters sent to the server. A modest response already fetched in full can instead be split into smaller visible pages in the interface. Infinite loading is another request-paging pattern: fetch the next batch and append it rather than replacing the current results.
The distinction is fundamentally about where computation and data transfer occur. Server paging conserves client memory and limits transfer, but repeated navigation depends on network access and API design. Client paging makes local sorting and filtering responsive, but can waste bandwidth if most fetched records are never viewed. Neither method is inherently superior. The right choice depends on dataset size, interaction patterns, and the service's capabilities, which is why the pagination chapter treats design as a content-specific problem rather than a visual widget choice.
Analysis
This book is both a programming tutorial and a tour of architectural choices. Its narrative starts with a familiar problem: a JavaScript interface gradually accumulates callbacks that synchronize data, HTML, and server requests. Backbone is presented as a modest organizing layer, not a machine that eliminates design decisions. Models, collections, views, events, and routers provide recognizable places to put those decisions. The practical exercises make the argument concrete, first with a browser-persisted todo list, then with a book library connected to a REST API.
The most durable contribution is the emphasis on responsibility and lifecycle. A model change should be observable; a view should be removable; a server representation should map reliably to client identity. These details turn architecture from a diagram into behavior that can be tested. The sections on Marionette, RequireJS, pagination, and jQuery Mobile extend the same concern into larger systems: reduce repetitive work, make dependencies visible, and keep competing lifecycle managers from interfering.
The book also resists treating MVC as a strict identity claim. Backbone's view absorbs event-handling duties, and the router manages URL state, so MV is a more honest description than textbook MVC. That precision matters because names influence implementation. The discussion of event aggregators and mediators similarly shows that identical mechanisms can serve different intentions.
The chief limitation is temporal. The examples describe a 2012 to 2013 JavaScript ecosystem, with specific versions of libraries and tools that should not be assumed to represent current practice. Their APIs are historical; their design questions remain recognizable. Backbone's minimalism shifts responsibility to developers, which is freedom for experienced teams and a source of inconsistent architecture for others. The practical lesson is not to adopt every named tool, but to identify where state, rendering, navigation, persistence, and cleanup belong, then choose the smallest structure that keeps those responsibilities legible.
Review Summary
Developing Backbone.js Applications receives mixed reviews, with an average rating of 3.69 out of 5. Readers appreciate its comprehensive coverage of Backbone.js and related technologies, praising the logical flow and good examples. However, some find it better suited for intermediate to advanced users rather than beginners. Critics note outdated content, incomplete code examples, and a lack of in-depth explanations. Despite these drawbacks, many still consider it a valuable resource for learning Backbone.js, especially when combined with hands-on practice and additional documentation.
Glossary
MV*
Model and view architectureA shorthand for JavaScript application architectures built around models and views, without insisting on a separate controller or on one exact interpretation of MVC. Backbone fits this description because its views often handle user events, while routers coordinate URL-based application state.
Backbone.Events
Object event systemBackbone's publish and subscribe utility, mixed into models, collections, views, routers, and other objects. Objects can register callbacks with on() or listenTo(), publish notifications with trigger(), and remove subscriptions with off() or stopListening(). It enables components to communicate without direct method calls.
listenTo()
Tracked event subscriptionA Backbone event method that lets one object subscribe to events on another while recording the relationship on the listener. Unlike a bare subscription made with on(), this makes cleanup straightforward: the listener can call stopListening() to remove some or all of its subscriptions. Backbone views use it to avoid stale callbacks and memory leaks.
ghost view
Unremoved view still listeningA view that is no longer needed by the interface but remains reachable because a longer-lived model or other object still holds a reference to one of its event callbacks. The view can continue responding to events and cannot be collected from memory. Using tracked subscriptions and stopping them when removing the view prevents this problem.
Backbone.sync
Persistence adapterThe function Backbone calls to perform model and collection persistence. Its default implementation maps create, read, update, partial update, and delete operations to HTTP methods and sends requests through a jQuery-compatible Ajax method. Developers can override it to connect Backbone to a different API or storage mechanism.
AMD
Asynchronous module definitionA JavaScript module format in which code declares its dependencies and exposes a module value. RequireJS implements AMD, loading modules and supplying their dependencies to a factory function. The format helps avoid implicit dependence on global variables and manually ordered script tags, and can support asynchronous or on-demand loading.
Marionette.Region
View lifecycle managerA Marionette object responsible for managing views displayed in a particular DOM element. When given a view, a region renders it and inserts its element. When another view replaces it, the region closes or removes the old view, helping centralize display and cleanup responsibilities.
CompositeView
Hierarchical collection viewA Marionette view designed to render a collection and its items within one composite structure. It can use a specified item view for each model, and it can support recursive presentation of nested collections. This reduces the custom code needed to display hierarchical data.
Backbone.Paginator.requestPager
Server-side collection pagingA Backbone.Paginator component for collections whose data source supports pagination. It constructs requests for selected pages and exposes navigation methods such as moving to the next page or a chosen page. It is useful when a client should request only a subset of a larger server-side result set.
Backbone.Paginator.clientPager
In-memory collection pagingA Backbone.Paginator component that divides data already loaded into the browser into pages for display. It can support local page navigation, sorting, and filtering without making a new request for every page. Its approach assumes the relevant dataset has already been fetched and is available on the client.
FAQ
1. What is "Developing Backbone.js Applications" by Addy Osmani about?
- Comprehensive Backbone.js guide: The book offers an in-depth introduction to Backbone.js, a lightweight JavaScript framework for structuring client-side web applications.
- Core concepts covered: It explains models, views, collections, routers, and how to build maintainable, modular single-page applications (SPAs).
- Hands-on learning: Readers are guided through practical projects like a Todo app and a Book Library app, with step-by-step exercises and real-world examples.
- Advanced topics included: The book also explores modular development, RESTful integration, testing, optimization, and popular Backbone extensions.
2. Why should I read "Developing Backbone.js Applications" by Addy Osmani?
- Improve client-side architecture: The book demonstrates how Backbone.js helps organize complex JavaScript-heavy applications, making code more maintainable and scalable.
- Practical, real-world skills: Through detailed examples and exercises, readers learn to build, test, and optimize real applications using Backbone and related tools.
- Covers advanced and common challenges: It addresses issues like modularization, memory management, and integration with other libraries, providing solutions for common Backbone.js pitfalls.
- Open and community-driven resource: Released under a Creative Commons license, the book encourages community contributions and is accessible to novice and intermediate developers.
3. What are the key takeaways from "Developing Backbone.js Applications" by Addy Osmani?
- Minimalist, flexible architecture: Backbone.js provides just enough structure—models, collections, views, and routers—without enforcing rigid patterns, allowing developers to adapt it to their needs.
- Event-driven and RESTful: The framework’s event system keeps data and UI in sync, and it integrates easily with RESTful APIs for server communication.
- Modular and scalable development: The book emphasizes modular code organization using AMD and RequireJS, making large applications maintainable and efficient.
- Testing and optimization: Readers learn best practices for testing with Jasmine and QUnit, and for optimizing production builds with tools like r.js.
4. What are the best quotes from "Developing Backbone.js Applications" and what do they mean?
- Minimal set of primitives: “The essential premise at the heart of Backbone has always been to try and discover the minimal set of data-structuring (Models and Collections) and user interface (Views and URLs) primitives that are useful when building web applications with JavaScript.” This highlights Backbone’s philosophy of simplicity and sufficiency.
- Embracing new perspectives: “One’s destination is never a place, but a new way of seeing things.” — Henry Miller. This quote encourages developers to adopt new approaches, like Backbone, to improve their craft.
- Importance of namespacing: “Without strong namespacing conventions, it is also fairly easy to pollute the global namespace with your own custom objects.” This underscores the need for modularity and clean code organization in JavaScript.
5. How does "Developing Backbone.js Applications" by Addy Osmani explain the MVC pattern and Backbone’s MV* approach?
- MVC basics explained: The book describes MVC as separating concerns into Models (data), Views (UI), and Controllers (input handling), with clear communication between components.
- Backbone’s MV variation:* Backbone merges controller responsibilities into views and uses routers for navigation, making it an MV* rather than strict MVC framework.
- Event-driven updates: Models and views communicate via an event system, keeping data and UI synchronized without direct coupling.
- Templating and routing: Views render templates (like Underscore or Handlebars), and routers manage application state and navigation for SPAs.
6. How do Backbone.js models, views, collections, and routers work according to Addy Osmani’s book?
- Models: Hold data attributes, support defaults and validation, and can persist data to a server using RESTful methods like save(), fetch(), and destroy().
- Views: Manage UI logic, render templates, and handle DOM events declaratively, listening to model changes to update the interface.
- Collections: Ordered sets of models with utility methods for adding, removing, filtering, and sorting, and can fetch data from servers.
- Routers: Map URL fragments to functions, enabling bookmarkable states and navigation in single-page applications.
7. What are the key features and benefits of Backbone.js highlighted in "Developing Backbone.js Applications"?
- Lightweight and flexible: Backbone provides minimal structure, allowing developers to build applications in their preferred style.
- Event-driven and RESTful: Rich event handling between models and views, and seamless integration with RESTful APIs for data persistence.
- Modular and scalable: Scales from small widgets to large applications, and works well with other libraries and frameworks.
- Readable and efficient: The source code is small and accessible, making it easy for developers to understand and extend.
8. How does Addy Osmani’s book guide building a Todo application with Backbone.js?
- Step-by-step architecture: The book walks through creating Todo models, collections, and views, demonstrating CRUD operations and UI binding.
- Templates and events: Uses Underscore.js templates for rendering and declarative event handling for user interactions like adding, editing, and deleting todos.
- Persistence with localStorage: Shows how to use Backbone.localStorage to persist data in the browser without a server.
- Routing and filtering: Implements URL-based filtering (all, active, completed) using Backbone.Router for bookmarkable app states.
9. How does "Developing Backbone.js Applications" by Addy Osmani recommend integrating Backbone.js with a RESTful backend?
- Separation of concerns: The frontend Backbone app communicates with a Node.js/Express REST API backend, modeling real-world client-server interaction.
- Model and collection setup: Models and collections are configured with URLs pointing to the REST API, enabling fetch(), save(), and destroy() to sync with the server.
- Handling nested data: The book addresses challenges like date formatting and nested attributes, showing how to parse and serialize data correctly.
- Server-side implementation: Guides setting up a MongoDB-backed REST API with CRUD routes, connecting Backbone apps to persistent storage.
10. What are MarionetteJS and Thorax, and how do they extend Backbone.js as described in Addy Osmani’s book?
- MarionetteJS: A composite application library that reduces boilerplate, manages memory and view lifecycles, and provides specialized view types and regions for layout management.
- Boilerplate reduction: Automates rendering logic and view cleanup, preventing memory leaks and zombie views.
- Thorax: An opinionated framework built on Backbone, using Handlebars templating and offering conventions for app organization and embedding child views.
- Flexibility and modularity: Both extensions allow developers to scale Backbone apps with better structure and maintainability, integrating seamlessly with existing code.
11. How does "Developing Backbone.js Applications" by Addy Osmani recommend modularizing applications using RequireJS and AMD?
- Asynchronous module loading: RequireJS loads JavaScript files asynchronously, improving performance and enabling dynamic module loading.
- AMD module definition: Modules are defined with define(), specifying dependencies and a factory function for clean dependency management.
- External templates and shimming: Uses RequireJS’s text.js plug-in for external templates and configures shims for non-AMD libraries like Backbone and Underscore.
- Organizing code: Encourages separating models, views, collections, and routers into folders, wrapping components as AMD modules for maintainability.
12. How does Addy Osmani’s book approach testing Backbone.js applications with Jasmine, QUnit, and SinonJS?
- Jasmine for BDD: Introduces Jasmine as a behavior-driven development framework for writing readable, automated unit tests with suites, specs, and spies.
- Testing models, collections, and views: Provides examples for testing defaults, validation, filtering, rendering, and DOM integration, using jasmine-jquery for fixtures.
- Asynchronous and spy support: Shows how to mock AJAX requests and write asynchronous tests, ensuring thorough client-server interaction testing.
- Comparison with QUnit and SinonJS: Explains QUnit’s straightforward assertions and modules, and how SinonJS adds spies, stubs, and mocks for detailed function call inspection.
Download PDF
Download EPUB
.epub digital book format is ideal for reading ebooks on phones, tablets, and e-readers.