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

Backbone.js Mixins

Backbone.js is a great javascript mvc framework to create frontend js heavy applications.

What happens when there you start building your backbone.js app but find that there is substantial boilerplate code that you want to reuse?

One cool feature, that’s not necessarily a part of backbone.js is mixins. If you’re familiar with Ruby, then it should be a familiar concept. Mixins are basically a way to inherit another class, or module and be able to use the inherited class’s functions/methods.

To create a mixin x in backbone, you use underscores nifty _.extend() method to allow an object to inherit some other objects methods.

Take the following silly example. If you wanted to reuse the functions in the ComplexMaths object, how would you do it with _.extend()?

complex_maths.js
1
2
3
4
5
var ComplexMaths = {
  addition: function(number1, number2){
      return number1 + number2;
  }
}

Simple

calculator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
Calculator = Backbone.View.extend({
  initialize: function() {
    _.bindAll(this, "blah...");
  }

  // ..
  // ..
  // ..

});

// Mixin here
_.extend(Calculator.prototype, ComplexMaths);

The final line of the script above, underscore accepts the destination object Calculator.prototype and duplicates the properties inside source object ComplexMaths into Calculator.prototype.

Now you have the power to create whole libraries of reusable useful stuff!