-
-
Save vicneanschi/cf246016a8a501b89121 to your computer and use it in GitHub Desktop.
Simple Client-side EventEmitter implementation
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
function EventEmitter() {} | |
EventEmitter.prototype.on = | |
EventEmitter.prototype.addListener = function (event, callback) { | |
this._events = this._events || {}; | |
this._events[event] = this._events[event] || []; | |
this._events[event].push(callback); | |
return this; | |
}; | |
EventEmitter.prototype.removeListener = function (event, callback) { | |
this._events = this._events || {}; | |
if (event in this._events === false) return; | |
this._events[event].splice(this._events[event].indexOf(callback), 1); | |
return this; | |
}; | |
EventEmitter.prototype.emit = function (event) { | |
this._events = this._events || {}; | |
if (event in this._events === false) return false; | |
for (var i=0; i < this._events[event].length; i++) { | |
this._events[event][i].apply(this, Array.prototype.slice.call(arguments, 1)); | |
} | |
return true; | |
}; |
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
function Foo() {} | |
Foo.prototype = Object.create(EventEmitter.prototype); | |
Foo.prototype.constructor = Foo; | |
Foo.prototype.sayHello = function () { | |
alert('Hello!'); | |
this.emit('greeted'); | |
}; | |
var foo = new Foo(); | |
foo.on('greeted', function () { | |
console.log('has said hello'); | |
}); | |
foo.sayHello(); // you will see "has said hello" in the console |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment