Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Created February 2, 2012 15:10
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ryanflorence/1723903 to your computer and use it in GitHub Desktop.
Save ryanflorence/1723903 to your computer and use it in GitHub Desktop.
events =
events: {}
bind: (topic, handler, context = this) ->
(@events[topic] ||= []).push { handler, context }
trigger: (topic, args...) ->
if @events[topic]?
event.handler.apply event.context, args for event in @events[topic]
var slice = Array.prototype.slice;
var events = {
events: {},
bind: function (topic, handler, context) {
if (context == null) context = this;
this.events[topic] = this.events[topic] || []
this.events[topic].push({ handler: handler, context: context });
},
trigger: function (topic/*, args...*/) {
if (this.events[topic] == null) return;
var args = slice.apply(arguments, 1);
for (var i = 0, l = this.events[topic].length, event; i < l; i++) {
event = this.events[topic][i];
event.handler.apply(event.context, args);
}
}
};
// just for comparison, that's the JS I'd hand write
// Not terribly difficult, but sure has a lot of "stuff"
# use as singleton
events.bind 'foo', (a, two) -> console.log a, two
events.trigger 'foo', 'a', 2
# mixin to other objects assuming a merge/extend function
merge SomeClass.prototype, events
instance = new SomeClass()
instance.bind 'foo', -> console.log 'hi'
instance.trigger 'foo'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment