Skip to content

Instantly share code, notes, and snippets.

@dvapelnik
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dvapelnik/e95f8b546d49ae0dec49 to your computer and use it in GitHub Desktop.
Save dvapelnik/e95f8b546d49ae0dec49 to your computer and use it in GitHub Desktop.
Simple EventEmitter and ingeriter like a Node.js EventEmitter and util.inherits
/** EventEmitter */
function EventEmitter() {
var registry = {};
this.getRegistry = function () {
return registry;
}
}
EventEmitter.prototype.emit = function (event, eventArgs) {
var
array,
func,
handler,
i,
type = typeof event === 'string' ? event : event.type;
var registry = this.getRegistry();
if (registry.hasOwnProperty(type)) {
array = registry[type];
for (i = 0; i < array.length; i++) {
handler = array[i];
func = handler.method;
if (typeof func === 'string') {
func = this[func];
}
func.apply(this, [eventArgs]);
}
}
return this;
};
EventEmitter.prototype.on = function (type, method) {
var registry = this.getRegistry();
var handler = {
method: method
};
if (registry.hasOwnProperty(type)) {
registry[type].push(handler);
} else {
registry[type] = [handler];
}
return this;
};
EventEmitter.prototype.off = function (type) {
var registry = this.getRegistry();
delete registry[type];
};
/** inherit */
function inherit(Constructor, SuperConstructor) {
Constructor.prototype = new SuperConstructor;
}
/** Illustration */
function Person(name) {
this.name = name;
}
inherit(Person, EventEmitter);
var man = new Person('Jimmy');
man.on('sayName', function (eventArgs) {
console.log(eventArgs);
console.log(this.name);
});
man.emit('sayName', {message: 'Will emit correctly'});
man.off('sayName');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment