Skip to content

Instantly share code, notes, and snippets.

@arboleya
Last active December 11, 2015 01:08
Show Gist options
  • Save arboleya/4520783 to your computer and use it in GitHub Desktop.
Save arboleya/4520783 to your computer and use it in GitHub Desktop.
MicroEvent in CoffeeScript.
###
Port of MicroEvent in Coffeescript with some naming modifications
and a new 'once' method.
Original project:
https://github.com/jeromeetienne/microevent.js
###
class MicroEvent
_init:-> @_listn or @_listn = {}
_create:(e)-> @_init()[e] or @_init()[e] = []
on:(e, f)-> (@_create e).push f
off:(e, f)-> (t.splice (t.indexOf f), 1) if (t = @_init()[e])?
once:(e, f)-> @on e, (t = => (@off e, t) && f.apply @, arguments)
emit:(e)-> l.apply @, ([].slice 1) for l in t if (t = @_init()[e])?; 0
@mixin=(t)-> t::[p] = @::[p] for p of @::; 0
@arboleya
Copy link
Author

HELP

1 - Extending

class MyClass extends MicroEvent

2 - Mixing In

class MyClass
  constructor:->
    MicroEvent.mixin @

3 - Emitting

class MyClass extends MyClass

  constructor:->
    @init()
    @emit 'init', ['initialized!']

4 - Listening

m = new MyClass
m.on 'init', ( status )-> console.log 'Status: #{status}'

4 - Unlistening

m.off 'init', ( status )-> console.log 'Status: #{status}'

@jjt
Copy link

jjt commented Jul 20, 2014

emit wasn't passing arguments. I fixed that in my fork:

emit:(e, r...)-> l.apply @, r for l in t if (t = @_init()[e])?; 0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment