Last active
August 29, 2015 14:09
-
-
Save lstebner/81e15299ac646cb71311 to your computer and use it in GitHub Desktop.
This class provides basic event interactions for on, off, one and trigger which can be inherited by any other classes
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
### | |
EventModel | |
built by Luke Stebner, November 2014 | |
This class is meant to be extended by other classes in order to provide basic event | |
functions including on/off/one/trigger. You've probably used these through other | |
frameworks such as Backbone or jQuery, but this class allows any data object to provide | |
this functionality in a very clean, simple way. | |
Example: | |
Extend from your class: | |
class GameData extends EventModel | |
now, say you have this: | |
game_data = new GameData() | |
you would now get access to: | |
game_data.on "data_updated", (new_data) => | |
// do something with new_data | |
game_data.update_game_data = -> | |
$.ajax | |
//ajax settings | |
success: (msg) => | |
@trigger "data_updated", msg.data | |
That's all there is to it! You can now fire events and pass data to callback listeners | |
without requiring any additional frameworks. | |
### | |
class EventModel | |
constructor: (@namespace="", @debug=true) -> | |
@listeners = {} | |
on: (what, fn) -> | |
if [email protected](what) | |
@listeners[what] = [] | |
@listeners[what].push fn | |
off: (what, fn) -> | |
found = false | |
if @listeners.hasOwnProperty(what) | |
for callback, i in @listeners[what] | |
if ""+callback == ""+fn | |
@listeners[what].splice(i, 1) | |
found = true | |
found | |
one: (what, fn) -> | |
@on what, fn | |
remove_fn = => | |
@off what, fn | |
@off what, remove_fn | |
@on what, remove_fn | |
trigger: (what, data=null) -> | |
found = false | |
if @listeners.hasOwnProperty(what) | |
for cb in @listeners[what] | |
cb? data | |
found = true | |
found | |
log: (msg) -> | |
return unless @debug | |
console.log "event", msg | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment