Last active
May 12, 2016 09:12
-
-
Save wiledal/2fd0b7a376e1f2aec07ba42909c6eea0 to your computer and use it in GitHub Desktop.
The basicest eventdispatcher
This file contains hidden or 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 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); | |
| } |
This file contains hidden or 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 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