Skip to content

Instantly share code, notes, and snippets.

@threepointone
Created July 12, 2012 10:11
Show Gist options
  • Save threepointone/3097182 to your computer and use it in GitHub Desktop.
Save threepointone/3097182 to your computer and use it in GitHub Desktop.
simple namespaced events in coffeescript
match = require 'minimatch'
_ = require 'underscore'
class Events
constructor: ->
@_events = [];
on: (evt, handler = _.i, scope = @) ->
@_events.push {evt, handler, scope};@
fire: (evt, args...) ->
_.each @_events, (spec) =>
if match evt, spec.evt then spec.handler.apply spec.scope, [{evt,_evt:spec.evt}].concat args;@
# simple handler
_h = (e) ->
console.log "matched #{e._evt} for evt #{e.evt}"
x = new Events
x.on 'a:*', _h
x.on '*', _h
x.on '*:b', _h
x.on '*:b:*', _h
# fire a bunch of events
x.fire 'a'
x.fire 'a:b'
x.fire 'a:b:c'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment