Skip to content

Instantly share code, notes, and snippets.

@wiledal
Last active May 12, 2016 09:12
Show Gist options
  • Select an option

  • Save wiledal/2fd0b7a376e1f2aec07ba42909c6eea0 to your computer and use it in GitHub Desktop.

Select an option

Save wiledal/2fd0b7a376e1f2aec07ba42909c6eea0 to your computer and use it in GitHub Desktop.
The basicest eventdispatcher
function EventDispatcher() {
this._listeners = {};
}
EventDispatcher.prototype.on = function(event, callback) {
if (!this._listeners[event]) this._listeners[event] = [];
this._listeners[event].push(callback);
}
EventDispatcher.prototype.trigger = function(event, data) {
if (!this._listeners[event]) return;
for (var i = 0; i < this._listeners[event].length; i++) {
this._listeners[event][i](data);
}
}
EventDispatcher.prototype.off = function(event, callback) {
if (!_this.listeners[event]) return;
var index = _this.listeners[event].indexOf(callback);
if (index > -1) _this.listeners[event] = _this.listeners[event].splice(index, 1);
}
function SomeClass() {
EventDispatcher.call(this);
// Do stuff
}
SomeClass.prototype = Object.create(EventDispatcher.prototype);
SomeClass.prototype.constructor = SomeClass;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment