Low fire danger web development
Low Fire Danger develops web applications for businesses and startups. We design, engineer and develop user experiences to make your web application a pleasure to use.
We will also help you with your business and strategise your online presence. Giving you advice and guiding you through every step, from conception to execution. Lets talk: contact@lowfiredanger.com.au

Extending Backbone.js Classes in CoffeeScript

Here’s a very quick how-to on extending backbone classes and over riding their methods in coffeescript. You can even call super; that will let you call the original method once you’re complete.

greeter.js
1
2
3
4
5
6
class Greeter extends Backbone.View
  initialize: () ->
      # Initialize things here

  greet: ->
      alert 'Hello'
multi_lingal_greeter.js
1
2
3
4
5
6
7
class MultiLingalGreeter extends Greeter
  initialize: () ->
  # Initialize things here

  greet: ->
      alert 'Bonjour'
      super

And now we can create a new instance of the MultiLingalGreeter class then call the greet method. We will get two alert boxes, the first one will say Bonjour, followed by Hello. This happens because super is being called, which calls the original method of the class

1
2
greeter = new MultiLingalGreeter();
greeter.greet() // Alerts 'Bonjour' followed by 'Hello'

What happens when we create another class that extends the MultiLingalGreeter? Will calling super inside greet() execute the Greeter class directly or only the method inside MultiLingalGreeter?

drunk_greeter.js
1
2
3
4
5
6
7
class DrunkGreeter extends MultiLingalGreeter
  initialize: () ->
  # Initialize things here

  greet: ->
      alert 'Aarhohhoah *spew*'
      super

Turns out, it’ll only call the method inside MultiLingalGreeter. The super method inside MultiLingalGreeter will then call the original Greeter class. So you’ll get alerts in the following order:

  1. Aarhohhoah *spew*
  2. Bonjour (called from the super inside DrunkGreeter)
  3. Hello (called from the super inside MultiLingalGreeter)

Conclusion: Backbone.js + Coffeescript is sexy isn’t it?