Skip to content

Instantly share code, notes, and snippets.

@davidaurelio
Created March 22, 2012 09:54
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save davidaurelio/2157422 to your computer and use it in GitHub Desktop.
Constructable mixins in JavaScript
/*
EventEmitter is usable as constructor and as mixin.
*/
function EventEmitter() {}
// this does the trick
EventEmitter.prototype = EventEmitter;
EventEmitter.addListener = function(type, listener) {
this.listeners(type, true).push(listener);
};
EventEmitter.emit = function(type) {
var eventsForType = this.listeners(type);
for (var i = 0, len = eventsForType.length; i < len; i += 1) {
eventsForType[i].apply(this, arguments);
}
};
EventEmitter.listeners = function(type, createIfMissing) {
var events = this._events || (createIfMissing ? (this._events = {}) : {});
return events[type] || (createIfMissing ? (events[type] = []) : []);
};
EventEmitter.removeListener = function(type, listener) {
var eventsForType = this.listeners(type);
var index = eventsForType.indexOf(listener);
if (index !== -1) {
this.splice(index, 1);
}
};
// In ES5: prevent tainting EventEmitter itself
Object.freeze(EventEmitter);
/*
Creation of an event emitter by using the constructor.
*/
var e = new EventEmitter();
e.addListener('foo', function(type, data) { console.log('e:', type, 'event', data) });
e.emit('foo', 12345);
/*
Use EventEmitter as mixin for other objects
*/
var f = mixin({/* other things here */}, EventEmitter);
f.addListener('foo', function(type, data) { console.log('f:', type, 'event', data) });
f.emit('foo', 12345);
function mixin(to, from) {
for (var name in from) {
to[name] = from[name];
}
return to;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment