Backbone.js in Action MEAP V02 - Chapter 1 - Manning Publications

bolivialodgeInternet and Web Development

Dec 14, 2013 (3 years and 10 months ago)

75 views




MEAP Edition
Manning Early Access Program
Backbone.js in Action
Version 2











Copyright 2013 Manning Publications


For more information on this and other Manning titles go to
www.manning.com


brief contents


P
ART
1:

J
AVA
S
CRIPT
MV*
1. Modern JavaScript with Backbone
2. Building a client-side application
3. Structure for Backbone applications
P
ART
2:

A
PPLICATION
B
UILDING
B
LOCKS

4. Models
5. Managing data with models
6. Collections
7. Views: Data, DOM and UI
8. Routing
9. Managing complex Backbone apps
P
ART
3:

S
TRUCTURE
,

P
ATTERNS
,
AND
E
XTENSIONS

10. Writing testable Backbone
11. Using modules in Modern applications
12. Enhancing Backbone with extensions and plugins



1
Modern JavaScript with Backbone
This chapter covers
 A brief history of JavaScript applications
 The MVC pattern and how it relates to Backbone
 The dependencies and pre-requisites for working with Backbone
 Backbone’s history and early development

Backbone is a library for structuring web applications. Since the dawn of the Internet,
forward thinking developers have known that it is more than just a means of serving static
HTML documents, but rather a platform made for applications. JavaScript has evolved into an
ecosystem that’s awash with libraries and frameworks for helping you write rich, interactive
front-end experiences; a modern web developer has many tools to choose from. The trouble
is that there are actually too many choices to make, and it is easy to end up with a messy,
unstructured application on your hands. Backbone helps solve this problem in a way that is
lightweight and flexible—Backbonewill bend to fit the problems you are trying to solve.
Even after almost two decades of consistent usage, there’s still a lot that JavaScript can’t
do.There’s even more that’s not terribly obvious when you set out building applications with
it, especially when it comes to assembling an interactive, single page user experience.
Backbone gives you generic tools for helping organize and structure front-end applications.
By focusing on mechanisms for managing your data and structuring interfaces around a
synchronous event system, Backbone provides structure in a world that encourages you to
created tangled piles of anonymous callbacks and jQuery selectors.

Caveat emptor: this book is not a definitive guide to JavaScript by any means. Rather, it’s
a companion to learning about the Backbone.js library. If you haven’t written a single line of
JavaScript, I’d suggest starting your JavaScript adventure elsewhere. But for those of you
who are just getting comfortable with JavaScript and need a quick refresher, an Appendix is
included that covers some of the basic terms and concepts that are used throughout this
book, including a primer on jQuery and Underscore. This book helps to fill the gaps left by
Backbone’s intentionally loose opinions about how to organize applications large and small,
drawing from the experiences of many developers as they have learned to use Backbone
effectively. In order to jump in and start writing the next great JavaScript application, it is
important to grasp some of the vocabulary and concepts that are baked in to the Backbone’s
vision of the world.
In this chapter we will explore the concepts that Backbone uses to build a foundation for
applications, examine the dependencies it relies on to staylightweight, and touch on some of
the problems Backbone solves best. Along the way, a lot of what we will discuss isn’t
exclusive to Backbone; many concepts are applicable to building JavaScriptapplications,
outside the context of any one library or framework. But in order to really know a person or
a discipline or library, you first must know where it came from.
1.1 In the Beginning, There Was JavaScript
When it was first conceived at Netscape in 1995, JavaScript was meant to give developers a
way to interact with web pages in the browser. Its primary programming interface is the
Document Object Model, a standardized set objects, functions and properties that represent
the state of the HTML document in the browser. Commonly referred to as the DOM, this set
of APIs is what allows JavaScript access to manipulate a page’s content and to respond to
user interaction. As we’ll see in Chapter 2, “the DOM is a mess” for several reasons, and this
sentiment inspired libraries like jQuery to simplify how you interact with web pages. But with
great power comes great responsibility: many developers have fallen into the trap of tying
up the state of their front-end application in the DOM by embedding information in markup,
using inline AJAX calls in a procedural fashion or otherwise making a bit of a mess when
wiring up interactive, dynamic applications.
For many years, JavaScript was viewed as a “toy” language that was not well suited for
doing much more than creating pop-ups, occasionally validating a form, or making some text
animate across the page. When not being conflated with Java, JavaScript took a backseat
role until, as if from nowhere, large, mature JavaScript applications began to pop up
everywhere. Dynamic, single page applications like Gmail and Google Maps showed that rich
user experiences were not only possible to implement in JavaScript, but that those
experiences could offer clean and boundary pushing user experiences that made traditional
multi-pageload apps look impossibly clunky by comparison.
Recently, the pace at which JavaScript evolved as a language had increased dramatically.
Fueled by competition between browser vendors, JavaScript performance was pushed
forward in leaps and bounds, widening the doors of what is considered possible and practical
to do in JavaScript. New standards and specifications like HTML5, CSS3 and ECMAscript 5
have led to a new generation of applications that are characterized by fast, well-designed
user experiences that have come to define some of the most trafficked sites on the Internet.
Simultaneously, the number of libraries, frameworks, and tools for writing JavaScript
underwent a similar renaissance. Open source projects like jQuery and Underscore created
layers of abstraction on top of the DOM and the “bad parts” of JavaScript to make it as easy
as possible for developers to manipulate pages, add animated effects, and respond to user
input.
By leveraging the functionality of other frameworks and libraries, the developers at
Document Cloud built a compact and potent library for creating and managing JavaScript
applications. Appropriately named, Backbone gives your applications just a few structural
components—the mainstays that you attach all of the functionality of your app to. Because of
its implementation-agnostic nature, Backbone works well in a wide variety of situations, from
embedded widgets like Disqus comments, to massive applications like USAToday.com. By
seeking to provide structure rather than to make a comprehensive API that covers every
edge case of every problem you’re likely to encounter, Backbone is uniquely flexible.
1.2 Patterns For Client-side Applications
If you are familiar with an Object Oriented programming language, you have likely come
across the term MVC before. The model-view-controller pattern is often found in server-side
frameworks like Ruby on Rails or Django, where its used to negotiate the storage,
presentation and management of data in a way that’s well-isolated and testable. As we’ll see
in the upcoming pages, Backbone borrows heavily from MVC and it’s derivative patterns—but
what emerges is something a bit different—the same metaphors are used, but they take on a
different meaning when applied in the browser. These patterns are colloquially know as MV*
when applied to front-end applications. But before we can dig into that ever-so-important
asterisk, we need to talk about MVC and why it even matters in the first place.
1.2.1 Model-View-Controller
In the simplest terms, MVC is used on the server to organize and separate concerns. By
keeping Models, Controllers and Views as distinct interfaces, its easier to add features or
making changes to an application over time. The alternative is to create what are known as
monolithic applications; apps that have all of their logic for display, persistence and
presentation all in one place. As illustrated in Figure 1.1, MVC provides a template for
structuring the different concerns of an application: Models represent the domain specific
knowledge and data in the application, and are capable of notifying observers of state
changes (changes to the underlying data they represent); Views typically represent the UI
layer, displaying model data and listening to changes in the model’s state; Controllers handle
user input and relay any changes that need to happen on the model layer.




1.1 A traditional Model-View-Controller relationship
The main problem addressed by MVC isthe tendency for monolithic applications to be
prone to difficult-to-solve bugs that result from complex logic or tightly coupled classes.
Tight coupling is a by-product of most procedural scripting languages and happens when a
single class is dependent on the inner workings or implementation details of another,
possibly unrelated class. For instance, the act of making database calls directly from a
presentational template is an example of tight coupling; the template is responsible for both
outputting an HTML template and communicating with a database or ORM to retrieve the
data its presenting. When these monolithic architectures are left unchecked, it becomes
difficult to test or isolate different areas of functionality. Structured and maintainable code is
important to developer productivity, and helps developers craft software more effectively.
MVC patterns address this problem by applying to divide the responsibilities in your
application.
1.2.2 Model-View-Presenter


1.2 The Model-View-Presenter Pattern
There are a host of similar patterns with similarly named acronyms, the most important
and most relevant to Backbone is the model-view-presenter pattern, or MVP. MVP is a
derivative of MVC, but shifts all of the “middle-man” functionality to a Presenter, rather than
wiring views and controllers directly to the model. Model-view-presenter (figure 1.2) is the
closest approximation to the relationships that exists between Backbone Core classes, your
server and the DOM. But try to not get hung up on the semantics of MVP vs. MVC vs. MV*--
the takeaway is that separating the areas of functionality in your application is the simplest
way to avoid monolithic architectures that are hard to grow, scale and change over time. The
assumptions you have about your software projects on day 1 tend to be way different on day
30 or day 60, so being flexible is a key trait of a successful developer or piece of software.
1.2.3 MV*, a Pattern for Real-World Applications
In client-side JavaScript applicationsthe need for patterns to help separate functionality is
just as much of a reality as it is on the server. If you’ve ever written an application with a
DOM abstraction library like jQuery, you’ve probably run into the problem of monolithic files,
where a lot of disparate functionality is crammed together into a single file. The main goal of
separating functionality is to reduce cognitive load, either for a future version of you or other
members of your team that might not have been around when the project was setup. In
Backbone, the diagram looks a little bit different.
Backbone combines the concept of a View and a Controller, which is similar to the
Presenter in MVP, as seen in Figure 1.3. But rather than making this a specific abstraction,
Backbone Views are bound to a piece of the DOM and are responsible for updating it. So a
Backbone View is really like a Presenter/Controller and a View, but it is still distinctly
separate from the DOM itself or the template it uses to format and present its data. This is
necessary because in JavaScript there is not a clean separation between the View layer (the
HTML / CSS) and the Controller or Presenter layer (the JavaScript that interfaces with DOM
APIs)—invariably JavaScript is going to be the primary interface for reading and updating the
state of the DOM, so having true isolation between the two layers isn’t all that practical.
Backbone also introduces the concept of a Router, which is a means of delegating and
initiating state changes in the application’s URL, either with hash URLs (that take the form
/#/posts/123) or with the HTML5 pushState API (which look like normal URLs, but don’t
cause a page reload when the URL changes.)

1.3 MV* in Backbone
Backbone doesn’t quite fit MVC,nor does it line up exactly with the MVP pattern; the term
that’s been coined to describe Backbone (and similarly minded frameworks) is, fittingly, MV*.
The asterisk denotes that there’s some grey-area around what the controller/presenter is
responsible for, since it’s largely up to the interpretation of the developer using Backbone in
their app.

1.3 Anatomy of Backbone Applications
Structure is the difference between order and chaos. While it’s certainly possible to build rich
frontend applications that exist in a single file and only rely on DOM methods or a single
DOM abstraction library, it’s usually an invitation to develop a large, monolithic and tightly
coupled application. But what is so wrong with that? If the code works shouldn’t that be the
deciding factor? Woe to the developer who continues down that logical fallacy—it’s a road
strewn with late nights and buggy software.
In a large application, it’s very easy to tie your state to the DOM and end up with a tangle
of jQuery selectors, inline HTML templates and anonymous callbacks, with no ability to replay
a given application state because of the sheer number of interdependent moving parts. It is
also plausible for a large application to contain thousands or tens-of-thousands of lines of
code. Managing your dependencies by hand or even creating ad hoc techniques to help
simply is not a sustainable practice. One of the decisions that this book strongly advocates is
to use some sort of module system—we will be using AMD modules in many of the examples,
with detailed information on modules in Chapter 10.
As we discussed in the previous section, Backbone applications are composed of 4 key
parts: Models, Controllers, Views and a Router. Along with a generic Events system,
Backbone is very modest in terms of what it offers, which turns out to be one of its biggest
strengths. Rather than trying to provide helpers and APIs that speak to every corner-case of
every implementation, the Backbone API is intentionally small, leaving the majority of the
decision-making in the hands of the implementer. While this is a huge strength for
Backbone, it also is a subtle weakness, because it also leaves a lot of room for
misinterpretation and opportunities to stray off the beaten path. The phrase that comes to
mind is “enough rope to hang yourself.”
When building any non-trivial JavaScript application, you will need something that’s a bit
more than just a few dozen lines in a jQuery document ready in one file.In order to start
breaking up front end problems into separate pieces of functionality and to start applying a
front-end flavor of MV*, it is import to understand how a web browser loads and interprets
JavaScript files as a page loads.
1.3.1 One file to rule them all
JavaScript began as a language meant to be embedded in webpages to interact with the
HTML document after it had been served.This is reflected in its sole loading mechanism, the
humble<script> tag. When a browser encounters a <script> tag, it pauses execution and
loads the content of the script, either from an external resource or from the body of the tag
itself. Naturally, this encourages small programs whose entirety would be contained within
the body of the <script> tag or in a single external file.
Due to the realities of having to load an additional file over the network for each
<script> tag on the page, there is an obvious penalty incurred on page load times if you
include lots and lots of JavaScript on the page. This makes for an environment where loading
a program that is comprised of lots of different files is not only cumbersome, but actively
discouraged. Of course, there are solutions to get over the synchronous and network
dependent nature of script tags: notably concatenation (combining several scripts into a
single file) and minification (compressing the contents of script by removing whitespace and
condensing variable names to reduce the network load as much as possible.)
To add insult to injury, JavaScript (as of ES5.1) still does not include an official module
system. Modules are just a way of encapsulating code so that it can be used externally and
are extremely important when it comes to writing applications that are large enough to
justify spread across multiple files and directories. In a language like Ruby, for instance, it’s
trivial to “require” the contents of another file such that they export a class or set of
functionality that you can rely upon and execute at your leisure in the file that’s requesting
them. Unfortunately, in JavaScript, this is a bit more complicated since there’s no
mechanism for replicating this exact behavior.
1.3.2 Modules: Take Your Pick
The most basic technique for encapsulating code into modules is to rely on global variables
for sharing code between files. Since the global scope is accessible by every script as it
executes, libraries, frameworks or your own custom code can modify global variables and
create applications composed of multiple files. This technique is highly dependent on the
order in which they’re included on the page. Up until a few years ago, this was the only way
to load reliably load your JavaScript dependencies: add a script tag that exposes the global
variable(s) you expect it to, add another script tag that depends on them, and you’re off to
the races. There are two main problems with this technique. For one, it takes a lot of
overhead to manage every script tag on your page, especially if you want to combine them
into a single file later. This means that you’re frequently editing the list of script tags, taking
great care not to disturb their order and also maintaining that same list of files elsewhere to
facilitate your build process. Secondly, it puts you in the business of managing modules in
the global namespace separately from your application state. As we will discuss in Chapter 3,
using a global variable to keep track of the various domain objects in your application is an
important technique for developing Backbone apps, and having to manage your modules in a
similar fashion only complicates the problem.

[ screengrab of tons of script tags ]

That sounds like a real headache for managing a simple application. In fact, for many
developers, keeping everything in a single file may seem like the best solution for avoiding
the problem altogether. Unfortunately, it is significantly easier to manage an application
when it’s organized into small, discreet chunks of functionality. Thousand line files put a lot
of burden on the parts of your brain that are better left to solve problems instead of having
to grok hundreds of lines of code at once to glean something about its structure. The trick to
composing applications that are spread across multiple files is to use one of the module
systems that exist to solve this exact problem.
There are two flavors of modules in JavaScript: asynchronous modules, which can
determine and load each file’s dependencies dynamically, and synchronous modules, which
need to go through a build process to determine the dependency graph and then combined
in the right order before they’re included on the page. These two module systems and their
specific implementations will be discussed in detail later on in this book, but for right now it’s
important to know that modules are the best way to separate functionality across different
files and as such the majority of examples presented will be using the AMD module format.
Regardless of which build system or method of delivery you choose, keep in mind that it’s
all been done before! Feel free to lean on tools like Backbone Boilerplate
(
https://github.com/tbranyen/backbone-boilerplate/
),Yeoman (
http://yeoman.io/
), or
Brunch (
http://brunch.io/
) to help get you started. They all have practical, common sense
conventions and will cut through a lot of the busy work when you start a new project. Keep
in mind that you don’t need a module system to write Backbone apps, but it makes some of
the problems of code organization, reuse and clean separation of concerns more manageable
in the long run.
1.3.3 M - Models and Collections
When you startplanning a Backbone application, a good first step is to analyze where the
data in your model is coming from. Maybe you already have a server with some JSON
endpoints, or you could be planning on building out a backend to suit your needs. Even if
you’re working with 3
rd
party APIs or just planning on saving locally in the Browser,
Backbone Models and Collections have you covered.
Models and Collections represent the data in your application and are usually meant to be
a mirror of tables in an external database. In the most common scenarios a Backbone Model
will have a one-to-one relationship with a row (or document) in a database. Out of the box,
Backbone will interface with RESTful resources without any additional setup. If you’re unsure
what a RESTful resource means, don’t worry—the REST pattern will be covered in detail in
Chapters 2 - 5. For a quick refresher, a RESTful resource is an API that follows a simple
pattern of name routes and HTTP methods to represent domain objects in the application,
and will usually read and write result to a database.
You may be asking, why make the distinction between Models and Collections? Couldn’t a
single interface be more effective to managing data returned from the server? While the
answer to that question may be “yes” in some cases, Collections are meant to be a way to
organize and interact with groups of models in a succinct manner. Instead of just storing
related models in an Array, putting them in a collection gives you the ability to sort, search,
filter and sync with the server transparently and automatically. Additionally, Collections emit
events for the various actions and state changes that they go through in their lifetime, so
you can have course grain controls for things like re-rendering.
1.3.4 V - Templates, DOM and Views
The most accurate way to map Backbone to the “Views” in Model-view-controller or Model-
view-presenter is to treat them as the complicated knot they are. The main problem is that
Backbone Views represent a chunk of the DOM, bound to a selector that can manage user
events and listen to Collection and Model events, rendering and re-rendering when data
changes. You may be thinking that’s more of the Controller or Presenter role in the MVC and
MVP diagrams from section 1.1 and you’re not too far off the mark. Backbone Views have a
lot in common with traditional Controllers or Presenters since they are responsible to reacting
to user input.
That’s where templates and the DOM come in. Both are the real means of presenting data
to the client and they usually represent Backbone Model or Collection data. If you’ve never
used templates before, they’re pretty simple. In JavaScript, there are only a few ways of
getting information from JavaScript to the DOM, and they all involve using strings to set the
content or attributes of DOM elements. Templates are an extension of the manual style of
making small chunks of markup. If you’ve ever been writing JavaScript for long enough,
you’ve probably done something like this (or at least seen it in another project):

var postTemplate = ‘<div class=”post”><a href=”/posts/’+ post.id +’”>’+
post.title +’</a><p>’+ post.body +’</p>”;

Essentially, that’s a simple JavaScript template, because at their core, templates are just
string concatenation. Notice how a <div> tag is built up from contents of several variables
Now, before we get ahead of ourselves—that much markup in your JavaScript should
immediate raise a red flag. Even in an example this small, it would be a good idea to store
that template in its own file and compile that into a template function.
A template library is a tool that takes strings (or files) that contain template contents and
delimiters and compile them into re-usable functions.Underscore (we’ll get to Underscore and
Backbone’s other dependencies in a moment) provides a utility method for compiling
templates. There are plenty of other popular template libraries to choose from, such as
Handlebars or Mustache. We’ll be covering how to best use templates later on in Chapter 7:
Backbone Views. Paired with a module loader or a build process, templates can have their
own files and directories, and are a good approximation of MVC views, since they literally
serve the single purpose of presenting model data.
The DOM is the other key constituent that makes up the “View” portion of Backbone’s
MVC. The DOM is where templates are ultimately written and provides the interface for
Backbone Views to bind events and accept user input. Backbone Views are really just a
simple object that’s associated with a piece of the DOM. Views can create their own element
or be attached to one that’s already on the page. They give you a simple syntax for
efficiently creating event handlers, searching for children elements and for setting and
manipulating their element with syntax borrowed directly from jQuery.

1.3.5 * - Routers, Views and Custom Code
Now to the grey area! The * or Controller/Presenter piece is the hardest to pin down and
relate directly to traditional MVC patterns, hence the asterisk. In Backbone, at least 2
different types of objects will fill the role of controller or presenter, depending on your
implementation and what criteria you’re using to evaluate them. Views can behave
controllers: they accept user input, passing data changes back to models and controllers.
Views are also the presentation layer of your application, determining how and when to
render an application state to the DOM. They can include helper methods for minimizing
template logic and are the first line of defense in your application—everything that a user can
do through your applications will usually start off in a view. But since they’re also intrinsically
tied to the DOM (even if you don’t specify a DOM element for a view, it will create one for
you behind the scenes,) views have a dual purpose and are an embodiment of the flexible
nature of MV* applications.
Routers can behave like controllers, too. In fact, Routers were names Controllers until
version 0.5.0.A Backbone router will typically house the delegation logic to determine which
views and models should be loaded to recreate an application state from a URL, another form
of user input. Because routers sit at the crux of most applications, its easy and tempting to
put business logic in route methods, choosing to persist data or take action when a certain
route is triggered. (This is an anti-pattern and the implications of writing “fat” routers will be
discussed in detail in Chapter 7.)
The thread that ties all of this grey area together is your own custom code. Backbone is
too small of a library (only about 1500 lines with comments at the time of writing) to create
applications for you auto-magically—it’s going to be up to you to implement your own
versions of these patterns; Models, Collections, Views and Routers are at your disposal to
shape your applications to fit the problems you need to solve. And again, that’s where the
asterisk comes in. Since Backbone gives you structural elements but does not impose
sanctions on exactly how to use them, the enforcement of any “rules” is entirely up to the
developer. Can Models and Collections know about DOM elements? Sure, if you really want
to. Can Views make AJAX calls to persist data to the server? Absolutely, but only at your own
risk. The takeaway is that while the Backbone core classes are inspired by patterns that have
helped developers solve problems in the UI world for 30+ years.This is indeed a brave new
world of JavaScript applications, and Backbone serves only to empower developers to re-use
code effectively, organize code efficiently, and make the next generation of rich web
applications.
1.4 Living in the JavaScript Ecosystem
Backbone couldn’t have appeared on the scene in late 2010 without owing a great deal to a
number of libraries and frameworks that paved the way for it. In order to understand why
it’s an impressive feat to pack so much power into such a small package, its important to
know a bit about the history of JavaScript libraries and where Backbone fits into the picture.
Without the work that went into Dojo Toolkit, Prototype.js and jQuery between 2004 and
2009, Backbone (and it’s companion Underscore) would probably not exist.
Many of the patterns (and anti-patterns!) that these libraries explored provided crucial
inspiration to the Backbone project, and in the case of jQuery, a soft dependency. We’ll
briefly explore the core features that Backbone and Underscore have gleaned from these
three libraries, and also touch on another important open source project that’s close to
Backbone’s lineage, Ruby on Rails.
1.4.1 Evolution Towards Backbone: Dojo Toolkit, Prototype.js, and Google
Closure
When the Dojo Toolkit was first written in 2004, the rich ecosystem of frameworks and
libraries that Backbone could rely on years later simply didn’t exist yet. Dojo helped create
that ecosystem. As a solution for building large-scale JavaScript application, Dojo promotes
modularity and code re-use. Dojo has a reputation for being difficult to learn and adopt due
to the large surface area of its API and the broadness of what it provides, but despite that
criticism, Dojo pioneered many of the patterns that are repeated in modern JavaScript
Libraries like Backbone and Underscore. Backbone doesn’t provide any direct compatibility
with Dojo, but Backbone applications have been incorporated into Dojo apps as widgets.
Although it’s fallen by the wayside in recent years, there aren’t too many places in the
JavaScript community that haven’t felt the influence of Prototype.js.Originally written by
Sam Stephenson in 2005, Prototype was the long-time default JavaScript library in Ruby on
Rails and was apoint of entry for many front-end developers during the height of its
popularity (including the author.) Prototype provides wrappers for DOM APIs, covering much
of the same territory (selectors, effects, AJAX) as jQuery.Perhaps the most memorable
aspect of Prototype was the heavy reliance on modifying native objects to add back
JavaScript’s “missing features.”Thing like convenience methods for manipulating data in
Arrays and Objects and improved DOM interaction methods were added directly into the host
environment, often times directly modifying pre-existing objects. In light of the fact that
most web sites run some amount of 3
rd
party JavaScript for things like analytics or
advertising, overriding natives can lead to breaking or unexpected behavior.
Backbone doesn’t provide any type of compatibility with Prototype, but it’s legacy for
adding back the “missing features” is continued in spirit by Backbone’s one required
dependency, Underscore. Underscore fills in the gaps for Arrays, Collections, Objects and
Functions by adding various convenience methods in all categories. But Prototype was
neither the first of the last library to inspire Document Cloud’s open source projects.
Google Closure is one of the grandparents of all modern JavaScript libraries and the
progenitor of Backbone’s constructor inheritance pattern. Developed alongside the initial
releases of Gmail, Google Maps and Blogger, Google Closure provides a rich panoply of
functionality and organizational structures.Despite a high barrier to entry (it has a big API),
Google’s JavaScript library is still used actively and has had a lasting impact on nearly every
framework and library that’s followed it. In fact, it’s the one non-dependent library that’s
referenced directly from the Backbone source.

1.4 Backbone cites `goog.inherits` as the progenitor if the `extend` method
The JavaScript community has come a long way in just a few short years. Intense
competition for market share between open source projects like Prototype, Mootools and
jQuery led to a renaissance of performance and usability. The cross browser inconsistencies
(which we’ll talk about in more detail in the next chapter) that plagued developers in the
early 2000s were glossed over by library implementers, putting the power to develop rich,
border-pushing applications into the hands of everyday software developers. No longer did
you have to work for a corporation like Google or Apple to have access to the high-quality
tooling necessary to develop complex client-side applications. By the end of the decade, the
landscape had changed significantly, and a new generation of open source, community
driven projects was leading the charge to once again empower developers to develop
applications with as little pain as possible. The clear-cut victor of these “framework wars”
was an up-and-comer DOM abstraction library named jQuery.
1.4.2 jQuery’s Rise to Popularity
jQuery is the most prominent of Backbone’s ancestors and is one of its optional
dependencies. Originally authored in 2006 by John Resig, jQuery quickly gained traction for
its easy to use API and focus on performance. Positioning itself as a DOM abstraction library,
jQuery introduced two novel concepts: a selector centric interface and chained syntax. By
exposing a single, unified interface that accepted CSS selectors as a means to find DOM
nodes, jQuery instantly improved years of verbose and questionably designed DOM APIs.

var posts = document.getElementById(‘posts’); #A
posts.style = “display: none”; #B

var comments = document.getElementByClassName(‘comments’); #C
for(var i=0; i < comments.lenght; i++){
comments[i].style = “display: block”; #D
}


$(‘#posts’).hide(); #E
$(‘.comments’).show();

A. Getting the element with the ID “posts”
B. Setting its CSS so it’s not visible on the page
C. Getting a NodeList of all elements with the class “comments”
D. Iterating over the list and setting each element’s CSS so it’s visible
E. jQuery’s syntax makes for much less code to accomplish the same thing

The second unique aspect of jQuery is its use of method-chaining, or when methods are
“chained together,” or called sequentially in a single statement. This makes jQuery syntax
very compact, since there’s no limit to how many methods you can call in a single statement.
When combined with the convenience of CSS selectors, jQuery’s API has proven to be
powerful, easy to learn and extremely popular.
Backbone uses jQuery for its DOM abstractions, notably selectors for scoping elements
to Views, event bindings for attaching delegate events (more on these in Chapter 6) and
jQuery’s AJAX method for simplified cross browser XHR. It’s an optional dependency because
Backbone only uses a small subset of the jQuery API and it only uses it in two main modules,
Views and Sync.
When you’re working in the browser, you should probably plan on including jQuery as a
dependency. If you find a compelling reason not to use it, know that it’s possible to swap it
out for something different (like Zepto.js) when that time comes. A brief overview of the
relevant portions of the jQuery API is included in Appendix B, but if you’re thirsty for more,
head over to
http://jquery.com
and check out their excellent documentation.
1.4.3 Ruby on Rails: a not-so-distant cousin
It might seem like a Ruby project wouldn’t be relevant to Backbone, but the popular MVC
web framework Ruby on Rails actually had a big influence on Backbone’s early development.
Document Cloud uses Rails internally to this day and Backbone was built as the JavaScript
framework for their application. In particular, the RESTful conventions that Backbone follows
are inspired directly by conventions from Ruby on Rails. The framework strives to place
“convention over configuration” and there by make it as easy as possible to write
applications.
With a focus on increasing the pace at which developers could stand up applications,
solve data modeling problems, and cutting down on the minutia of responding to HTTP
requests, Rails was the distillation of years of best practices for writing web servers. It also
placed a heavy focus on RESTful resources, or resources that are based on conventions of
HTTP methods and URL naming conventions, which is specifically relevant to Backbone’s
default options for interfacing with web servers.
RESTis an acronym for Representational State Transfer; in the broadest sense, REST
lays out a simple pattern to follow for creating, reading, updating and destroying domain
objects that are persisted in a database.

Action
HTTP Method
URL
Create POST /posts
Read GET /posts/<id>
Update PUT / PATCH /posts/<id>
Destroy DELETE /posts/<id>
Table 1.1 shows the combinations of RESTful actions with HTTP methods and URLs
REST conventions are what allow Backbone to integrate with most APIs out of the boxby
making the same assumptions about HTTP Methods and URLs as their mapped to the actions
you perform to a model. If you are already using RESTful endpoints on your server, wiring up
a Backbone model or collection is trivial; if you don’t have a server with RESTful endpoints,
it’s not the end of the world, you’ll just need to modify Backbone.sync to accommodate
whatever conventions your server follows. If you don’t know the answer to either of those
questions, don’t worry; these techniques are discussed in details in Chapters 4 and 5.
1.5 Backbone and Underscore: Early Releases
Released in 2009 and 2010, Backbone.js and Underscore.jsare open source components of
the Document Cloud project. Document Cloud is a joint venture between major newspaper
publishers to create an open, online catalog of primary source documents and a tool for
annotating, organizing and publishing them on the web.
Underscore was the first of the two to be released and began to gain followers due to its
familiar chained syntax and its similarities to parts of the Ruby standard library. It seemed
like familiar territory for the same developers who a few years earlier turned to Prototype.js
to add back some of JavaScript’s missing features, but with an easy to learn API that worked
well along side jQuery—something that Prototype couldn’t easily claim. Underscore also
innovated by using ECMAscript 5 native functions whenever possible. If a native version of a
function, like
Array.indexOf
, existed when Underscore first loaded, it would default to
using the native, and only would rely on custom fallbacks when the natives it relied on were
missing. This approach of feature detection wasn’t new or novel, but Underscore helped
normalize the technique and presented a path to use “new” browser features transparently in
all browser environments. Underscore is advertised as a tool-belt library: it puts just enough
useful tools close at hand, justifying it’s weight in the process.
More recently, Underscore has been forked by a performance and standards-driven
version of the same API, called Lodash. Lodash is meant to be a drop in replacement for
Underscore but adds in some extra features, like optional build steps and built-in AMD
compatibility, all while pushing the boundaries of JavaScript performance on the client. Many
developers have chosen to use Lodash instead of Underscore for these reasons. Since both
libraries use the exact same API, we’ll be simply referring to Underscore throughout the
book, but feel free to use whichever library you prefer.
Backbone was released in the fall of 2010 to little fanfare. It had many of its core
concepts already fleshed out, like Models, Collections, Views and Events, although it was
notably missing Routers (confusingly called Controllers when they first appeared in 0.3.0)
and a unified Sync function (which would be in place by the time 0.1.1 was released.)
Backbone started to gain followers on Github and additional project committers and
maintainers, as the project began to be used in more and more projects. Developers
gravitated towards backbone because it offered a solution to disentangling their jQuery-
centric applications in a way that did not involve learning some enormous toolkit’s API.
Early on, Backbone’s core developers made choices to focus on keeping things small and
positing that the library will be more effective in more situations by sticking to a small
number of core concepts, and doing them well. This approach has been divisive: many
feature requests are closed on the grounds of falling outside of “Backbone’s philosophy,” and
should be better off as plugins. As a result of this dogmatic defense of library size, Backbone
has managed to remain small despite thousands of commits from dozens of contributors.
The complete documentation can be found at
http://backbonejs.org
and the most up to
date source code can be checked out from Github
(
https://github.com/documentcloud/backbone
). Backbone’s source code is rigorously tested
and commented, so it’s easy (but not always inviting) to read through the source and run the
unit tests locally. Project source code is always the irrefutable truth about what a project
does and doesn’t do; I encourage you to take every opportunity to explore Backbone by
reading the annotated source code (
http://backbonejs.org/docs/backbone.html
) as soon as
you’re curious how something works and are not satisfied by what is printed in the
documentation.
1.6 Problems Backbone Solves
Backbone is a very small library compared to frameworks the likes of Dojo Toolkit or jQuery
UI.It’s not meant to be a comprehensive solution, but rather a skeleton that you’ll decorate
with your own functionality (as an aside, I’ll be avoiding corpus metaphors, except where its
truly appropriate.) Backbone is small enough to leave out opinions about your
implementation; it’s not concerned with reinventing the JavaScript object model or providing
a comprehensive HTML widget set. If used properly, Backbone gets out of way and lets you
focus on the problems that are important to your app.
Backbone gives you structure in the places where you need it most without making too
manyassumptions about your data structures or the problems you’re trying to solve. And
most of the decisions it makes for you can easily be undone. Don’t have a RESTful API to
plug into? Overwrite Backbone.sync to conform to your server stack to effect how every
model and collection in your app handles posting and retrieving data from the server, or
over-ride sync on individual models or collections if that’s more appropriate. Backbone won’t
mind at all. The only unalterable assumptions are that you’ll ultimately be dealing with JSON
representations of your data, but its still possible (though not recommended) to work with a
server that returns XML, you’d just have to use custom sync, parse, and toJSON methods on
those models and collections.
The only dependencies to use Backbone in the browser are the expectation of an
Underscore-like API mapped to the
_
variable and a jQuery-like API that’s mapped to the
$
.
By not wanting to re-invent any wheels, Backbone chooses to rely on its dependencies
heavily, but leave enough room to choose alternate implementations if you need to. This is
one of the main reasons why Backbone is being used as a viable piece of server-side
software in the Node.js community (more on apps with shared client and server code in
Chapter 11.)
This book covers the things that you might not consider when sitting down to write your
first Backbone application. In Backbone’s documentation, one section stands out. “There’s
more than one way to do it,” is a bold proclamation for a library to make. In short, there’s a
large gap between what Backbone provides you and outlines in its documentation, and the
real world implementations that go into building an application with it. This gray area
includes everything from references between models and views, to nested model and
collection relationships, to templating engines and how to render your UI. This book is about
making the right choices that fit the problems you need to solve and weighing the trade offs
between all those different ways of doing it.
1.7 Summary
Building modern JavaScript applications is complicated business. A plethora of choices stand
between a developers’ vision and the actual work of implementing it; choosing between
libraries, frameworks, build processes and development tools is just the tip of the iceberg
when developing a complex JavaScript application. Backbone helps simplify some of those
choices, while still leaving the door open for you to custom tailor your implementation to fit
the needs of your project. We’ve seen how Backbone is composed of distinct components
that fit together in a larger pattern and how those patterns help to separate and organize
concerns when building different type of applications. We have also looked at how Backbone
smartly relies on its dependencies, even though the landscape (jQuery or Zepto? Underscore
or Lodash?) might seem a bit fractured at first glance.
In the next chapter we’re going to dive headlong into what it takes to build a Backbone
application from scratch, and how you can start bending it to fit the needs of the problems
you need to solve. We’ll be using Backbone to transform a commenting system from a static,
multi-pageload workflow into a smooth, single page experience. This will allow us to explore
how Backbone integrates with pre-existing services while using it to improve and enhance a
traditional application experience, and is an excellent starting point for getting your feet wet
with Backbone.