Last active
March 20, 2018 21:42
-
-
Save moqmar/1a33e871e9a4b855443d57d40f56d052 to your computer and use it in GitHub Desktop.
Event Emitter
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
// Minimal Event Handler | |
// Call makeEmitter(obj) to make obj an event emitter. | |
// obj.on(event, handler) | |
// obj.off(event[, handler]) | |
// obj.fire(event[, args...]) | |
// https://gist.github.com/moqmar/1a33e871e9a4b855443d57d40f56d052 (Public Domain/CC0) | |
function makeEmitter(obj) { | |
obj.__l = {}; // Listeners - this.on("update", fn) -> { update: [fn] } | |
obj.on = function(ev, fn) { | |
if (!this.__l[ev]) this.__l[ev] = [fn]; | |
else this.__l[ev].push(fn); | |
}.bind(obj); | |
obj.off = function(ev, fn) { | |
if (!this.__l[ev]) return; | |
if (!fn) return delete this.__l[ev]; | |
var i; while ((i = this.__l[ev].indexOf(fn)) > -1) this.__l[ev].splice(i, 1); | |
if (!this.__l[ev].length) delete this.__l[ev]; | |
}.bind(obj); | |
obj.fire = function(ev) { | |
if (!this.__l[ev]) return; | |
var args = Array.prototype.slice.call(arguments, 1); | |
for (var i = 0; i < this.__l[ev].length; i++) this.__l[ev][i].apply(this, args); | |
}.bind(obj) | |
} |
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 makeEmitter(i){i.__l={},i.on=function(i,t){this.__l[i]?this.__l[i].push(t):this.__l[i]=[t]}.bind(i),i.off=function(i,t){if(this.__l[i]){if(!t)return delete this.__l[i];for(var _;(_=this.__l[i].indexOf(t))>-1;)this.__l[i].splice(_,1);this.__l[i].length||delete this.__l[i]}}.bind(i),i.fire=function(i){if(this.__l[i])for(var t=Array.prototype.slice.call(arguments,1),_=0;_<this.__l[i].length;_++)this.__l[i][_].apply(this,t)}.bind(i)} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment