Created
November 28, 2014 22:06
-
-
Save Narazaka/6cffe0b25431ce5340fd to your computer and use it in GitHub Desktop.
event listener
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
on: (event, callback) -> | |
unless event? and callback? then throw Error 'on() event and callback required' | |
unless @listener? | |
@listener = {} | |
unless @listener[event]? | |
@listener[event] = [] | |
if -1 == @listener[event].indexOf(callback) | |
@listener[event].push(callback) | |
off: (event, callback) -> | |
if event? and callback? | |
if @listener[event]? | |
index = @listener[event].indexOf(callback) | |
if index != -1 | |
@listener[event].splice(index, 1) | |
else if event? | |
delete @listener[event] | |
else if callback? | |
for event of @listener | |
index = @listener[event].indexOf(callback) | |
if index != -1 | |
@listener[event].splice(index, 1) | |
else | |
delete @listener | |
trigger: (event, args...) -> | |
if @listener?[event]? | |
for callback in @listener[event] | |
setTimeout (-> callback(args)), 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment