This introduction to Backbone + CoffeeScript focuses on two pressing questions: Why should you choose Backbone for your project? Why should you choose CoffeeScript? Despite our bias for this charming pair, we'll discuss the pros and cons of each, and mention some alternatives.

First, however, let us quickly make sure you're in the right place.

Intended Audience

This book is an introduction to Backbone, intended for JavaScript developers who enjoy programming in CoffeeScript. It is not appropriate for someone who is new to JavaScript. Also, it does not attempt to teach CoffeeScript, other than indirectly by example. Since CoffeeScript is JavaScript, with syntax borrowed from Python and Ruby, programmers familiar with these languages should be able to understand the CoffeeScript in this book without much trouble. To assist such readers, short explanations of CoffeeScript syntax appear here and there in the text, but only briefly, in order not to distract from the Backbone content.

If you feel that you might benefit from studying a little CoffeeScript before reading this book, I highly recommend Alex MacCaw's The Little Book on CoffeeScript. Naturally, the CoffeeScript project page is also an invaluable reference that overflows with helpful examples. It provides an interactive environment that you can access by clicking the Try CoffeeScript tab.

In addition to having experience with JavaScript, and some knowledge of CoffeeScript, you should be comfortable with jQuery. Let's try a little test: Does the following code example make sense to you? Can you add the missing line that is needed in order to bind the showMessage function as a click handler on the button, so that the message is displayed when you click it?

After making your changes in the interactive editor below, click the Run button to the right to execute the code. (To revert back to the original content, click the dropdown arrow just to the right of the Run button and choose Restore to original example.)

coffeescript-jquery-test
showMessage = (event) ->
  event.preventDefault()
  alert "You passed!"

button = $("<a href='#' class='btn'>Click me</a>")

# Add line here

editor.out.html button

You're still with us? Congratulations. You must know a thing or two about jQuery, and are not having any trouble with basic CoffeeScript. If this particular question stumped you for some reason, you may still do fine with the book: As we shall learn in the chapter on Views, Backbone wraps a number of interactions with jQuery in a convenient, declarative style. It is simply a good idea to be familiar with jQuery in order to understand how many things in Backbone work under the hood.

On the other hand, there is also the possibility that the content of this book will be too basic for you. If you already have significant real-world experience with Backbone and CoffeeScript, it may not be the book you are looking for. It is an introductory text, concerned with helping newcomers to Backbone progressively build an understanding of both its high-level concepts and its moving parts.

Why Backbone?

Backbone is a JavaScript library that helps you decouple presentation logic from domain logic and persistence. Considerable effort has been expended trying to determine where Backbone fits within the alphabet soup of MVC, MVP, MVVM, and related patterns of application architecture, but its creator simply labels it MV-whatever.

No matter what you call it, Backbone provides clarifying structure for your client-side code. Because it is a small framework, it focuses carefully on a few core value propositions. These include an event infrastructure that facilitates code decoupling, assistance with server interaction, and support for manipulating browser history.

History

While working at DocumentCloud, a Knight Foundation funding recipient, Jeremy Ashkenas extracted Backbone from the DocumentCloud codebase and released it as an open-source project in October, 2010. Backbone received attention in February, 2011, when 37signals revealed it at the core of an innovative architecture for mobile Web applications. Since mid-2011, its rise has been stratospheric. To see a few highlights of Backbone's adoption in the industry, scroll down the examples section of the project home page.

Strengths

The simple principle of code separation that Backbone embodies can bring a lot of value to your project, but to an experienced JavaScript developer, it is not earth-shattering. You may say: What is the big deal? Where is the magic? I've done something like this myself without even thinking about it!

You've just come into contact with one of Backbone's most profound qualities: It's just not that hard to understand how it works. This is a good thing.

In order to remain both physically small and conceptually easy to understand, Backbone's creators maintain carefully drawn limits to its responsibilities. The precise formula that makes Backbone arguably one of JavaScript's greatest libraries, instead of being just another also-ran, finds its origin in this restraint. It is a design philosophy that is attuned to the resource-constrained environment of Web browsers, especially on mobile platforms, as well as to the variety of needs in Web development, where ease and flexibility are critical to widespread adoption.

For example, Backbone takes a deliberately flexible stance regarding your UI code, as well as many other details of your implementation. This flexibility makes it suitable for projects of just about any size, from the most complex browser-based applications down to some quite humble little in-page features. Because Backbone mandates so little (even templates are optional, for example), it scales down very well, effectively providing value in the context of quite diminutive features and widgets. Taken as a whole, the amount of ceremony imposed by Backbone will not grossly outweigh the benefit delivered except in microscopic scenarios. The case has been made that you can improve less than a dozen lines of JavaScript by introducing Backbone.

This cohesion and certainty of purpose is no accident. Jeremy Ashkenas' resilience throughout the contentious history of CoffeeScript (more on that below) has proven his ability as a firm and resolute leader. He is also committed. Sometimes founders of successful open-source projects discover after a while that the success of one project has taken from them the time to explore new ideas and found new projects. Ashkenas, however, has not shown any sign of this tendency, and appears to be just as engaged and vigilant with his major projects now as when they were young and new.

Concerns

Because Backbone is unopinionated in so many areas, it leaves many decisions to you. This is not entirely good. The energy drained away by decisions about generic questions of application design can amount to a serious productivity drag on your project.

Also, since Backbone's restrained approach precludes it from magically wiring up the moving parts of your application, in a project of any significance you end up writing what may come to feel like boilerplate code. The solution is to extend Backbone to dynamically eliminate the duplication, either by yourself or by using a third-party plugin. However, this means that you spend time either writing or integrating a solution to a generic concern, rather than moving forward with your application.

Alternatives

There is a fantastic discussion of the current crop of client-side JavaScript libraries and frameworks in Steven Sanderson's recap of the 2012 Throne of JS conference. I highly recommend reading Steven's post from top to bottom, as well as visiting the project pages for Knockout, Ember.js, AngularJS, Spine, Batman.js, CanJS, and last but not least, Meteor.

For most people, especially newcomers, I would not recommend the cumbersome, monolithic JavaScript frameworks that dominated the previous era. While productive within a narrow range, such frameworks quickly become an obstacle to users who need to customize UI behavior. While they are extensible, the complexity involved in customization is often prohibitive for developers without a deep (and costly) learning investment.

However, there is a middle path in which frameworks provide more UI support than Backbone, but still without extending control over the complete landscape of widgets, layout, and CSS. If you would like to learn more, Ember.js is a good place to start.

Resources

If you have a pressing question about Backbone that you think could be answered easily by anyone with a measure of experience, ask it in the official #documentcloud channel on Freenode IRC. If you do not have an IRC client installed, there are a number of Web-based solutions that you can use to join the channel, including webchat.freenode.net.

Of course, before asking a question, you should do your best to hunt first for an existing answer on the Web. I recommend searching generally as well as directly in the official project GitHub issues, the unofficial StackOverflow backbone.js tag, and the unofficial backbonejs Google Group. These are also good places to post questions and issues that are longer, involve more than a line or two of source code, or for which you hope to gather multiple responses.

Why CoffeeScript?

Also created by Jeremy Ashkenas, but not from DocumentCloud, CoffeeScript is a high-level programming language that compiles into JavaScript, another high-level language. While this may sound unusual, the situation owes to JavaScript's strategic placement as the only ubiquitous, natively-supported programming language for Web browsers.

In fact, there is a long list of languages that do the same thing. What makes CoffeeScript special?

Most significantly, CoffeeScript does not attempt to add features to JavaScript. Remember the key role of restraint in Backbone's winning design? Ditto CoffeeScript: By working within the existing features of JavaScript, and limiting its contributions to syntax, CoffeeScript has managed to sweeten the experience of JavaScript programming without actually changing it much.

History

CoffeeScript arrived on GitHub in December, 2009, with the comment: "initial commit of the mystery language." According to the marketing site for Marc-André Cournoyer's book How to Create Your Own Freaking Awesome Programming Language, creator Jeremy Ashkenas used the book's system to create CoffeeScript, writing "It's been a lot of fun, and surprisingly little work to get a language that covers 95% of what JavaScript can do."

Ashkenas soon converted the original Ruby compiler to one written in CoffeeScript itself. One year after introducing the language, he announced the 1.0 version, on December 24, 2010.

During late 2010 and early 2011, CoffeeScript received high-profile endorsement from 37signals programmers Sam Stephenson and David Heinemeier Hansson, culminating in the commit in April 2011 that made CoffeeScript a default in the popular Ruby on Rails framework. For just a taste of the controversy that has accompanied CoffeeScript's rise in popularity, read through the comments on that commit.

Strengths

CoffeeScript has taken the world by storm. It has broken into GitHub's list of the top ten most popular programming languages, displacing Objective-C, and it has been a default in the Ruby on Rails framework for Web development since April 2011.

This stunning success rests on many good qualities, but most notable among them in my opinion is CoffeeScript's beauty. Before you breeze by this point in search of something more tangible to present to your CTO, consider this glove thrown by renowned open-source JavaScript developer Sam Stephenson: CoffeeScript is Beautiful & I Never Want to Write Plain JavaScript Again.

A programmer's sense of beauty is rarely gratuitous, and indeed CoffeeScript's is rooted in the concise, efficient way in which its syntax allows you to accomplish your goals. Under the hood, things are hardly a mess. The JavaScript output is surprisingly readable, considering that the primary goals for it are safety and speed.

Speaking of safety, the project page states that CoffeeScript "is an attempt to expose the good parts of JavaScript in a simple way." And the bad parts? CoffeeScript either hides them away completely, or makes them less handy.

Concerns

As mentioned earlier, CoffeeScript's rise in popularity has not been without controversy: The choice of the language used on a project is significant and not a decision to be made lightly.

Certainly, if you have a successful, productive team of experienced JavaScript programmers who are not interested in using CoffeeScript, do not force it upon them. Also, if you are trying to attract developers to your project, you may wish to remain flexible on the topic, although advertising for CoffeeScript skills may be a way to attract some good people.

If your organization is split over whether to switch to CoffeeScript, conducting a trial that is limited to test code (for which its concise function syntax is very well suited) may offer an acceptable way for your organization to gain some experience with it.

The fact that CoffeeScript adds a compile step may be a concern for projects lacking an infrastructure such as the Ruby on Rails asset pipeline. However, in practice it is not much trouble to run the command-line coffee utility with the --watch flag.

Debugging CoffeeScript is probably its greatest theoretical drawback, although in practice I personally have not had much trouble with it. In any case, JavaScript source maps promises an imminent solution to this issue.

Alternatives

The best alternative to CoffeeScript is obvious: JavaScript!

However, the fact that you are here indicates an openness to JavaScript alternatives, and there is nothing wrong with considering the dozens of languages listed at the altJS site. Another noteworthy option is Iced CoffeeScript, which extends CoffeeScript in order to simplify asynchronous programming.

Resources

As with Backbone, the best places to go for help with CoffeeScript are the official #coffeescript channel on Freenode IRC, the official project GitHub issues, the unofficial StackOverflow coffeescript tag, and the unofficial CoffeeScript Google Group.

About this Book

One of the objectives of the ScriptyBooks project is to reduce barriers to active coding while you learn. By adapting the classical form of written text to an interactive, online experience, the platform encourages you to interact with the examples and make them your own.

The chapters that progress through the Backbone components (Models, Collections, Views, and Routers) are best read in order. The Quick Tour compresses some of the same material into a very small space, with a different example. The chapters Setup and Structure, Eco Templates, and JSON APIs are somewhat independent and may be skipped if desired, although naturally I recommend reading them.

Interactive Examples

The vast majority of the example code in this book is presented using interactive CodeMirror editors. I encourage you to actively tinker with the examples.

A basic editor looks like this.

editor-example-sum
sum = (a, b) -> a + b

In addition, some listings exercise the code presented with a touch of TDD/BDD. This is done with should-style assertions powered by the Chai library.

editor-example-sum-test
sum(2, 3).should.equal 5

You can execute the code, including the assertion, by clicking on the Run button to the right of the each editor. An assertion that proves false raises an error, halting execution. The output of the error will be displayed below the editor in a red bubble.

Even editors which are not intended to be run by themselves as presented will reveal the Run button if you click on them. This is because you may change them at any time into something you might like to run. (By running a CoffeeScript example, you verify that it compiles correctly into JavaScript, even if there is no other visible result than the blue Pass bubble. As you can see in the two examples above, some editors depend on previous editors. You should be able to infer these relationships from the text of the book.

Examples also include HTML templates that are compiled using Eco (Embedded CoffeeScript templates).

templates/output
<div>
  Some <em><%= @message %></em> template output.
</div>

The compiled template function can be retrieved from the global JST object by the title displayed to the top left of the listing.

editor-template-test
content = JST['templates/output'](message: "dynamic")

editor.out.html content

In order to display output from the example code, the editor object provides the following utility functions:

  • editor.log(message) - Appends the message argument to the blue Pass bubble

  • editor.out.html(content) - Replaces the content of the blue Pass bubble with the content argument using the jQuery html function

  • editor.out.append(content) - Appends the content argument to existing content of the blue Pass bubble using the jQuery append function

If you still feel unclear about the usage of these editors, don't worry. The examples in this book are generously surrounded with reminders and explanation.

Source Code

The example code in this book is available for download from quartzmo/backbone-coffeescript on GitHub. For status updates on the release of the example code, please watch the repository on GitHub and/or follow @scriptybooks on Twitter.


This chapter is part of the interactive book Backbone + CoffeeScript.