Skip to content

Instantly share code, notes, and snippets.

@dynajoe
Last active August 29, 2015 14:01
Show Gist options
  • Save dynajoe/214a3ed0490219377360 to your computer and use it in GitHub Desktop.
Save dynajoe/214a3ed0490219377360 to your computer and use it in GitHub Desktop.
Extending Objects
var EventEmitter = require('events').EventEmitter;
var MyNewEmitter = function () {
EventEmitter.call(this);
var that = this;
setInterval(function () {
that.emit('myEvent');
}, 1000);
};
MyNewEmitter.prototype = Object.create(EventEmitter.prototype);
MyNewEmitter.prototype.constructor = MyNewEmitter;
MyNewEmitter.prototype.on = function (eventName, callback) {
console.log('Hey! Someone subscribed to ' + eventName);
EventEmitter.prototype.on.call(this, eventName, callback);
};
var MyNextNewerEmitter = function () {
MyNewEmitter.call(this);
};
MyNextNewerEmitter.prototype = Object.create(EventEmitter.prototype);
MyNextNewerEmitter.prototype.constructor = MyNextNewerEmitter;
MyNextNewerEmitter.prototype.on = function (eventName, callback) {
console.log('Another layer of indirection');
MyNewEmitter.prototype.on.call(this, eventName, callback);
};
var emitter = new MyNextNewerEmitter();
emitter.on('myEvent', function () {
console.log('Event fired');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment