Skip to content

Instantly share code, notes, and snippets.

@jaseemabid
Created January 24, 2014 22:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaseemabid/8607832 to your computer and use it in GitHub Desktop.
Save jaseemabid/8607832 to your computer and use it in GitHub Desktop.
Tiniest, simplest pubsub ever
/*jslint nomen: true*/
'use strict';
var Pubsub = function () {
this._events = {};
};
Pubsub.prototype.on = function (type, handler) {
if (this._events[type] === undefined) {
this._events[type] = [];
}
this._events[type].push(handler);
};
Pubsub.prototype.trigger = function (event, message) {
var events;
if (this._events[event] instanceof Array) {
events = this._events[event];
events.forEach(function (e) {
e.call(this, message);
});
}
};
Pubsub.prototype.off = function (type) {
if (this._events[type]) {
delete this._events[type];
}
};
// ---------------------------------------- //
var broker = new Pubsub();
broker.on('foo', function (m) {
console.log('Got the message ', m);
});
broker.trigger('foo', 42);
broker.trigger('foo', 26);
broker.off('foo');
broker.trigger('foo', 'Never show this');
// ---------------------------------------- //
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment