Ever use jQuery and think the .bind()
and .trigger()
APIs are nice? Here is a small class you can use when writing CoffeeScript to quickly implement the observer pattern in your own objects.
For more involved scenarios, consider using a library like RxJS.
# this: https://gist.github.com/464257 in coffeescript, without the global stuff...
class EventsDispatcher
callbacks: {}
bind: (event_name, callback) ->
@callbacks[event_name] ||= []
@callbacks[event_name].push callback
@
trigger: (event_name, data) ->
@dispatch event_name, data
@
dispatch: (event_name, data) ->
chain = @callbacks[event_name]
callback data for callback in chain if chain?
class Connection extends EventsDispatcher
connect: ->
@trigger 'connected'
something = new Connection()
something.bind 'connected', ->
console.log 'i connected!'
something.connect()