m0w3dw
Last Updated: February 25, 2016
·
2.255K
· jaysoo
571cd899248d35ac14382559520a570b

CoffeeScript mixins in Backbone

This will allow you to use mixins in your Backbone models, views, collections, and routers.

include = (mixins...) ->
    throw new Error('include(mixins...) requires at least one mixin') unless mixins and mixins.length > 0

    for mixin in mixins
      for key, value of mixin
        @::[key] = value unless key is 'included'

      mixin.included?.apply(this)
    this

Backbone.Model.include = Backbone.Collection.include = include
Backbone.View.include = Backbone.Router.include = include

Then you can do:

Foo =
  # Executes when included
  included: ->
    @message = 'Hello World!'

  # This method will be mixed in
  bar: -> console.log @message

class MyView extends Backbone.View
  @include Foo

view = new MyView
view.bar()  # prints 'Hello World!
Say Thanks
Respond

1 Response
Add your response

17453
Dea1ed917b13a1e6c12b9b12b262ec41

Thanks for this. The only issue I ran into was trying to use super in the instance methods since Coffeescript will error due to detecting super being called outside of an instance method when it parses the mixin code.

I got around this by manually finding/calling the super method:

@Foo =
  bar: () ->
    # Do something...
    # Falling back to super if found
    if superMethod = @constructor.__super__[arguments.callee.name]
      superMethod.apply @, arguments

If you know of a better way, please let me know!

Erik

over 1 year ago ·