Created
March 22, 2012 09:54
-
-
Save davidaurelio/2157422 to your computer and use it in GitHub Desktop.
Constructable mixins in JavaScript
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 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); |
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
/* | |
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); |
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
/* | |
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