Created
January 19, 2012 17:08
-
-
Save davidcornu/1641217 to your computer and use it in GitHub Desktop.
Allows CoffeeScript classes to trigger their own events and allow binding to them.
This file contains hidden or 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
class EventedClass | |
bind: (event, callback) -> | |
@eventHandlers ||= {} | |
@eventHandlers[event] = [] unless @eventHandlers[event]? | |
@eventHandlers[event].push(callback) | |
return true | |
unbind: (event, callback) -> | |
@eventHandlers ||= {} | |
if @eventHandlers[event]? && @eventHandlers[event].indexOf(callback) >= 0 | |
@eventHandlers[event].splice(@eventHandlers[event].indexOf(callback), 1) | |
return true | |
else | |
return false | |
unbindAll: -> | |
@eventHandlers = {} | |
return true | |
trigger: (event, data={}) -> | |
@eventHandlers ||= {} | |
if @eventHandlers[event]? && @eventHandlers[event].length > 0 | |
for callback in @eventHandlers[event] | |
callback(data) if typeof(callback) == 'function' | |
return true | |
else | |
return false | |
window.EventedClass = EventedClass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you man for sharing this, helped me a lot :)