Skip to content

Instantly share code, notes, and snippets.

@tobyhinloopen
Created April 10, 2012 14:10
Show Gist options
  • Save tobyhinloopen/2351639 to your computer and use it in GitHub Desktop.
Save tobyhinloopen/2351639 to your computer and use it in GitHub Desktop.
EventEmitter = {};
EventEmitter.bind = function(event_name, fn) {
this.handlers || (this.handlers = {});
this.handlers[event_name] || (this.handlers[event_name] = []);
this.handlers[event_name].push(fn);
return this;
};
EventEmitter.emit = function(event_name) {
if(!this.handlers || !this.handlers[event_name] || this.handlers[event_name].length == 0) return;
var i = 0, fn = null;
var argsArray = Array.prototype.slice.apply(arguments);
argsArray.shift();
for(; i<this.handlers[event_name].length; i++)
this.handlers[event_name][i](argsArray);
return this;
};
EventEmitter.registerClassEvent = EventEmitter.registerClassEvents = function(klass, events) {
var events = events.split(" ");
var i = 0, event = null;
for(; i<events.length; i++)
(function(event_name) {
klass.prototype[event_name] || (klass.prototype[event_name] = function(fn) { return this.bind(event_name, fn); });
})(events[i]);
klass.prototype.bind || (klass.prototype.bind = EventEmitter.bind);
klass.prototype.emit || (klass.prototype.emit = EventEmitter.emit);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment