Last active
December 23, 2015 00:45
-
-
Save davepeck/4356801 to your computer and use it in GitHub Desktop.
Fun with coffeescript and callback patterns.
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
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 | |
@ |
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 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" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just noodling with the idea. A simple helper to build an eventing pattern. I considered using generic
on
andfire
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.