Mixins in CoffeeScript

So, we’ve finally achieved a small utility function that implements mixins in Coffee. In Javascript too :-)

Implementation might not yet be super clean, but it allows us to:

  • mix all methods of mixin class into a base class
  • mix many classes into a base class
  • a mixin has a place for constructing its data if necessary
  • a mixin can read&modify “base” class’ data
  • a base class can read&modify mixin data (awkward, but works)

In short:

and implementation is bit hacky, but works. Uses underscore.js and modified hashmal’s Mixin.
One small requirement of this solution is all roles must extend Mixin class.

A longer example of what’s possible along with part of our Jasmine test:

class Nothing
constructor: (@name=”nothing”) ->

doSomething: =>
“I cannot do anything”

class Presenter extends Mixin
presentYourself: =>
“My name is #{@name}”

doIPlay: =>
“I play with many #{@players}”

class Game extends Mixin
setup: =>
@name = ‘Monopoly’
@players = []
@players.push “David”

sayHello: =>

something = new Nothing()

ObjectHelper.addRole(something, Presenter)
expect(something.presentYourself()).toBe(‘My name is nothing’)
ObjectHelper.addRole(something, Game)
expect(something.sayHello()).toBe(‘My name is Monopoly’)
expect(something.doIPlay()).toBe(‘I play with many David’)

something.name = ‘something’
expect(something.presentYourself()).toBe(‘My name is something’)

something.players.push “John”
expect(something.doIPlay()).toBe(‘I play with many David,John’)


And stripped down whole Mixin.coffee

 So, happy mixxxxing to you :-)