Last active
August 6, 2017 10:57
-
-
Save afterburn/b809f8082abb6cd0667e364b95a6091b to your computer and use it in GitHub Desktop.
Basic JavaScript PubSub 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 PubSub() { | |
this.events = []; | |
} | |
PubSub.prototype.on = function(namespace, fn) { | |
this.events[namespace] = this.events[namespace] || []; | |
this.events[namespace].push(fn); | |
} | |
PubSub.prototype.off = function(namespace, fn) { | |
if(this.events.hasOwnProperty(namespace)) { | |
for(var i=0;i<this.events[namespace].length;i++) { | |
if(''+this.events[namespace][i] === ''+fn) { | |
this.events[namespace].splice(i, 1); | |
break; | |
} | |
} | |
} | |
} | |
PubSub.prototype.emit = function(namespace, args) { | |
if(this.events.hasOwnProperty(namespace)) { | |
this.events[namespace].forEach(function(fn) { | |
fn(args); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Basic PubSub implementation
This implementation converts functions into strings for comparison. The reason for this decision is that otherwise you would need to store a function in a variable for it to be evaluated to true when comparison occurs in the off method (explained in greater detail here). I've also chosen to use prototypes instead of defining methods in the constructor because performance is better with the former as well as preventing inheritance issues (both explained in greater detail here).
Usage