Last active
August 29, 2015 14:19
-
-
Save dvapelnik/e95f8b546d49ae0dec49 to your computer and use it in GitHub Desktop.
Simple EventEmitter and ingeriter like a Node.js EventEmitter and util.inherits
This file contains 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
/** 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