I needed the ability to override and invoke mixed in methods (ala super) closer to how ruby handles modules. And the simple extension method would clobber the mixin method if it existed in the class. Since I'm building it all in CoffeeScript I have access to the super object which lets me shim methods in. It will also automatically merge the events object so you can define event handlers in the mixin.
_.extend Backbone,
mixin: (klass, mixin, merge) ->
debugger unless mixin
mixin = mixin.prototype || mixin
merge ||= ["events"]
sup = _.extend({},klass.__super__)
for name,func of mixin
if base = sup[name] && _.isFunction(base)
sup[name] = ->
func.apply this, arguments
base.apply this, arguments
else
sup[name] = func
hp = {}.hasOwnProperty
prototype = klass.prototype
for name,func of mixin
continue unless hp.call(mixin,name)
continue if _(merge).contains name
prototype[name] = func unless prototype[name]
klass.__super__ = sup
_(merge).each (name) ->
if mixin[name]
prototype[name] = _.extend({},mixin.events,prototype.events)
@
Usage
class SimpleView extends Backbone.View
events:
"click .show" : "show"
calculate: ->
super + 5
show: ->
console.log @calculate()
class CalculatableViewMixin
events:
"click .calculate" : "show"
calculate: ->
15
Backbone.mixin SimpleView, CalculatableViewMixin