Using Backbone.js with CoffeeScript
If you start writing an application using Backbone.js and Coffeescript as we did recently, you’ll quickly discover that they are both great tools. However, what you may not notice right away if you’re new to Coffeescript is that there are certain parts of Backbone’s example Todos application that become unnecessary or clunky if translated verbatim to CoffeeScript. Following are a few little things that we found made our code a bit more concise.
CoffeeScript provides its own syntax for declaring classes—use it. It works perfectly with the way classes are set up in Backbone and will let us use other nice features of CoffeeScript (like the instance variables below). Instead of declaring a new class using the
extend method like this:
extends like this:
Use the power of the Fat Arrow:
Coffeescript will take care of binding methods to this if you declare a function using the fat arrow
=> instead of the skinny one
->. This means you don’t need to use
_.bindAll. For example, instead of this relatively naive translation of the example application’s TodoView initialize and render methods:
You can do this instead:
Use @variable instead of this.variable
If you’re like me, you’ll quickly tire of typing
this.variable to get at your instance variables. Again, Coffeescript has a shorter syntax that mirror’s Ruby’s instance variable syntax that you can use. The above example becomes this:
These changes may not seem like a big deal when viewed in the limited context of a small example application, but when combined with many of the other great features provided by CoffeeScript they have cleaned up our real application’s code considerably.