Skip to content

Instantly share code, notes, and snippets.

@davepeck
Last active December 23, 2015 00:45
Show Gist options
  • Save davepeck/4356801 to your computer and use it in GitHub Desktop.
Save davepeck/4356801 to your computer and use it in GitHub Desktop.
Fun with coffeescript and callback patterns.
Function::event = (name, initial_cb) ->
@prototype["fire_#{name}"] = (args...) ->
@__callbacks ?= {}
@__callbacks[name] ?= []
initial_cb.apply @, args if initial_cb?
callback.apply @, args for callback in @__callbacks[name]
@
@prototype["on_#{name}"] = (cb) ->
@__callbacks ?= {}
@__callbacks[name] ?= []
@__callbacks[name].push cb
@
class Foo
@event 'bar_finished', (a) -> @handle_bar_finished a
handle_bar_finished: (a) -> alert "Indoor #{a}."
bar: (a) ->
@do_something()
@fire_bar_finished a
do_something: ->
x = new Foo()
x.on_bar_finished((a) -> alert "Outdoor #{a}.")
x.bar "cat"
@davepeck
Copy link
Author

Just noodling with the idea. A simple helper to build an eventing pattern. I considered using generic on and fire methods but I like the explicitness better, I think?

Also, I really don't like jQuery's "call this method to trigger an event or register an event handler" anti-pattern.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment