Created
January 24, 2014 22:13
-
-
Save jaseemabid/8607832 to your computer and use it in GitHub Desktop.
Tiniest, simplest pubsub ever
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
/*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