Skip to content

Instantly share code, notes, and snippets.

@vicneanschi
Forked from liamcurry/eventemitter.js
Last active August 26, 2015 13:28
Show Gist options
  • Save vicneanschi/cf246016a8a501b89121 to your computer and use it in GitHub Desktop.
Save vicneanschi/cf246016a8a501b89121 to your computer and use it in GitHub Desktop.
Simple Client-side EventEmitter implementation
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;
};
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