Skip to content

Instantly share code, notes, and snippets.

@afterburn
Last active August 6, 2017 10:57
Show Gist options
  • Save afterburn/b809f8082abb6cd0667e364b95a6091b to your computer and use it in GitHub Desktop.
Save afterburn/b809f8082abb6cd0667e364b95a6091b to your computer and use it in GitHub Desktop.
Basic JavaScript PubSub implementation.
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);
});
}
}
@afterburn
Copy link
Author

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

var pubsub = new PubSub();

pubsub.on('test', data => {
    console.log(data);
});

pubsub.emit('test', 'Hello world!');// outputs 'Hello world!'.

/////////////////////////////////////////////////////////////////////////////////////

pubsub.off('test', data => {
    console.log(data);
});

pubsub.emit('test', 'Hello world!');// event was removed, so nothing happens.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment