We're hiring!

We're actively seeking developers for our new Detroit location. Learn more

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:

Use CoffeeScripts class and 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.

Jason Porritt (37 Posts)

As a software developer at Atomic Object, Jason has used .NET, RubyMotion, JavaScript, and everything in between to build a wide variety of web a mobile applications.

This entry was posted in Web Apps and tagged , . Bookmark the permalink. Both comments and trackbacks are currently closed.

13 Comments

  1. Posted May 10, 2011 at 1:01 pm


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

    can be simpler:


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

    you don’t have to write “return” statement, because last expression is always returned in CoffeeScript (similiar to ruby)

    • Posted August 12, 2011 at 1:00 pm

      I knew you could use the @ at the end and it would “return this” but personally I thought that might be a tiny bit confusing to people and it looks weird when you have a nested block before it

      classFunc: ->
          someVar = 1
          @collection.each ->
              # do some stuff
              processTask task
       
          @

      I prefer blank lines in-between statements (usually). Personal preference, it’s cool CoffeeScript doesn’t care.

  2. Jamie van Dyke
    Posted May 23, 2011 at 10:14 am

    I’m not sure, but in that last example I think you can go even further with the ‘this.’ translations:

    Forked Gist

    • Jason Porritt
      Posted June 9, 2011 at 9:13 am

      Yes, you are correct, Jamie. As Tomasz pointed out above, we could take the ‘this.’ translations further. Interestingly, I found it felt odd at first because I’m used to seeing @ associated only with variables, not function calls. However, I am slowly getting more comfortable with @ meaning ‘this.’ in non-variable contexts.

  3. Jason Miesionczek
    Posted May 24, 2011 at 1:12 pm

    So what is your workflow for working with CoffeeScript + Backbone? What web framework do you use?

    • Jason Porritt
      Posted June 9, 2011 at 9:20 am

      Jason, we are writing a mobile web application that communicates with a JSON API (a separate project). For the mobile web app itself we’re using Staticmatic2 to generate static assets from our Haml, Sass, and Coffeescript. The JSON API was written in .NET.

  4. GeorgeR
    Posted August 21, 2011 at 10:40 pm

    It would be great if you could fix the missing snippets!

  5. GeorgeR
    Posted August 21, 2011 at 10:41 pm

    Oh wait they just showed up. What.

  6. Mosselman
    Posted January 3, 2012 at 6:17 am

    Hi, thank you for the great tips! There is one thing I got stuck on though, using the fat arrow instead of _.bindAll didn’t do the trick for me. I had some problems with ‘Cannot call ‘xyz’ of undefined when I refered to ‘this’ (or @). When I DID use _.bindAll there were no problems. It really is a shame, because in the past, before using coffeescript, I had some bugs as the result of forgetting to include or remove _.bindAll arguments.

    Despite this, the whole post is great as a quick reference to coffeescript snippets for backbone.js.

    Thanks!

  7. Posted April 16, 2012 at 1:52 pm

    You can also condense $(@el) to @$el which is the view’s el pre-wrapped for you.

  8. Posted April 27, 2012 at 5:07 pm

    You can turn it to be a bit more idiomatic CoffeeScript,

    $(@el).html(this.template(@model.toJSON()))

    turns into this:

    ($ @el).html(@template @model.toJSON())
  9. Posted October 6, 2012 at 8:04 pm

    Hey just wanted to give you a quick heads up. The text in
    your content seem to be running off the screen in Firefox.
    I’m not sure if this is a formatting issue or something to do with internet browser compatibility but I thought I’d post to let you know.

    The design look great though! Hope you get the problem solved soon.
    Thanks

  10. Posted November 22, 2012 at 8:19 am

    Hey there! I just wanted to ask if you ever have any trouble with hackers?

    My last blog (wordpress) was hacked and I ended
    up losing a few months of hard work due to no back up. Do you have any methods to protect against hackers?

4 Trackbacks

  1. By 迟到的第一百八十一天 面对 on May 16, 2011 at 7:22 pm

    [...] the other stuff.How CoffeeScript makes jQuery more fun than ever.Using Backbone.js with CoffeeScript.SpaceX的航天传奇——商业公司击败举国体制的典范。 第一百八十天 [...]

  2. [...] Using Backbone.js with CoffeeScript | Atomic Spin Så här snyggt blir det när du kör Backbone och CofeeScript tillsammans! [...]

  3. [...] Using Backbone.js with CoffeeScript | Atomic Spin – [...]

  4. By Backbone.js Support | Atomic Spin on May 24, 2012 at 9:12 am

    [...] example uses CoffeeScript. You can see a little more about using Backbone.js and CoffeeScript in a previous [...]