Skip to content

Instantly share code, notes, and snippets.

@lstebner
Last active August 29, 2015 14:09
Show Gist options
  • Save lstebner/81e15299ac646cb71311 to your computer and use it in GitHub Desktop.
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
###
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 !@listeners.hasOwnProperty(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