Cocktail: DRY up your backbone code with mixins

July 24, 2012 Onsi Fakhouri

I’ve continued to enjoy using Backbone.js to build single page apps. As I’ve seen more and more real world backbone I’ve started to develop opinions to augment the blissfully unopinionated little framework that could.

One of these opinions has turned into a mini-library: Cocktail adds functionality to Backbone’s extend to facilitate breaking up reusable code into mixins. It’s pretty straightforward:

  1. Define your mixin. Mixins are just plain vanilla JavaScript objects with methods and properties hanging off of them. Here’s a slightly contrived mixin that makes a view selectable:

    window.MyMixins = {};
    MyMixins.SelectMixin = {
      initialize: function() {
        this.model.on('change:selected', this.refreshSelect, this);
      events: {
        click: 'toggleSelect'
      render: function() {
      refreshSelect: function() {
        this.$el.toggleClass('selected', this.model.get('selected'));
      toggleSelect: function() {
        this.model.set('selected', !this.model.get('selected'));
  2. Mix your mixin into your views. It’s a one-liner:

    var MyView = Backbone.View.extend({
      mixins: [MyMixins.SelectMixin, MyMixins.SomeOtherMixin],
      events: {
        'click .myChild': 'myCustomHandler'
      initialize: function() { ... },
      render: function() { ... },
  3. That’s it! Instances of MyView will automatically inherit the behaviors and methods defined in SelectMixin.

Cocktail brings two simple things to the table:

  • it adds the special mixins:[...] notation to Backbone’s extend.
  • it automatically detects and handles method collisions. In the example above Cocktail will wrap MyView‘s and SelectMixin‘s implementations of initialize into one method and assign that method to the new, composite, class. The return value of this composite method is the last non-undefined value returned by the methods it wraps. All colliding methods are handled this way, as is the events hash (the events hashes all get merged together).

There are more details and examples at the repo. In particular, there’s an example for testing mixins with Jasmine — it goes over a pattern for writing shared behaviors in Jasmine.

About the Author

Onsi Fakhouri

Onsi Fakhouri is the Senior Vice President, Cloud R&D of Pivotal.

High Level Features of the UAA
High Level Features of the UAA

The User Account and Authentication Service (UAA) in Cloud Foundry is responsible for securing the platform...

PHARTS: A Proposed Metric for Measuring Basketball Player Value
PHARTS: A Proposed Metric for Measuring Basketball Player Value

As a data guy, I have always enjoyed learning about the power of statistics combined with the right metric(...

SpringOne 2022

Register Now