Skip to content

Instantly share code, notes, and snippets.

@jkarmel
Last active December 10, 2015 23:08
Show Gist options
  • Save jkarmel/4506733 to your computer and use it in GitHub Desktop.
Save jkarmel/4506733 to your computer and use it in GitHub Desktop.
CoffeeScript Mixin Class. Extend it to create mixin functionality.
class Mixin
@mixin: (Klass)->
# Class methods
Klass[key] = val for key, val of @ when key != 'mixin'
# Instance methods
Klass::[key] = val for key, val of @prototype
class Extra extends Mixin
@fn: -> alert 'class fn called'
fn: -> alert 'instance fn called'
class Base
baseClassFn: -> 'baseClassFn called'
baseInstancefn: -> 'baseInstanceFn called'
Extra.mixin Base
Base.fn() #'class fn' alerted
b = new Base
b.fn() #'instance fn' alerted
# Also, you can use this right in the class definition!
class Base2
Extra.mixin @
baseClassFn: -> 'baseClassFn called'
baseInstancefn: -> 'baseInstanceFn called'
Base2.fn() #'class fn' alerted
b2 = new Base2
b2.fn() #'instance fn' alerted
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment