Created
July 12, 2012 10:11
-
-
Save threepointone/3097182 to your computer and use it in GitHub Desktop.
simple namespaced events in coffeescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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