17 Comments

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 classes

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:


window.TodoView = Backbone.View.extend({
...

Use CoffeeScripts class and extends like this:


class window.TodoView extends Backbone.View
...

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:


initialize: ->
  _.bindAll(this, 'render', 'close')
  this.model.bind('change', this.render)
  this.model.view = this

render: ->
  $(this.el).html(this.template(this.model.toJSON()))
  this.setContent()
  return this

You can do this instead:


initialize: ->
  this.model.bind('change', this.render)
  this.model.view = this

render: =>
  $(this.el).html(this.template(this.model.toJSON()))
  this.setContent()
  return this

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:


initialize: ->
  @model.bind('change', this.render)
  @model.view = this

render: =>
  $(@el).html(this.template(@model.toJSON()))
  this.setContent()
  return 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.