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.
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.
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.)
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.
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.
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.
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.
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.
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.
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.
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.
In fact, there is a long list of languages that do the same thing. What makes CoffeeScript special?
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.
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.
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.
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
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.
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.
sum = (a, b) -> a + b
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.
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).
<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.
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
messageargument to the blue Pass bubble
editor.out.html(content)- Replaces the content of the blue Pass bubble with the
contentargument using the jQuery html function
editor.out.append(content)- Appends the
contentargument 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.
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.