public
Last active

Simple PubSub snippet for both browser and nodejs (just remove outer wrap-function).

  • Download Gist
example-jquery.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/* Use PubSub on e.g. jQuery */
PubSub.apply($);
 
function addText(text) {
$('body').append('<p>' + text + '</p>');
}
function logChange(text) {
console.log('new text: ' + text);
}
 
/* Subscribe */
$.subscribe('textInput', addText);
$.subscribe('textInput', logChange);
 
/* Publish */
$('form').submit(function () {
var text = $('input[name=text]').val();
$.publish('textInput', [text]);
});
 
/* Unsubscribe */
$.unsubscribe('textInput', logChange);
example.js
JavaScript
1 2 3 4 5 6 7 8 9 10
var pubsub = new PubSub();
 
/* Subscribe */
pubsub.subscribe('topic', fn);
 
/* Publish */
pubsub.publish('topic', [arg1, arg2, ..., argN]);
 
/* Unsubscribe */
pubsub.unsubscribe('topic', fn);
pubsub.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
// pretty - 582 bytes (260 bytes gzipped)
 
(function (exports) {
"use strict";
 
exports.PubSub = function () {
var index = {};
 
this.publish = function (topic, exposure) {
var subscribers = index[topic],
i = subscribers.length;
while (--i + 1) {
subscribers[i].apply(this, exposure || []);
}
};
this.subscribe = function (topic, subscriber) {
(index[topic] = index[topic] || []).push(subscriber);
};
this.unsubscribe = function (topic, subscriber) {
var subscribers = index[topic],
i = subscribers.length;
while (--i + 1) {
if (subscribers[i] === subscriber) {
subscribers.splice(i, 1);
}
}
};
};
}(window));
 
 
 
// minified - 280 bytes (178 bytes gzipped)
 
(function(f){f.PubSub=function(){var e={};this.publish=function(a,d){for(var b=e[a],c=b.length;--c+1;)b[c].apply(this,d||[])};this.subscribe=function(a,d){(e[a]=e[a]||[]).push(d)};this.unsubscribe=function(a,d){for(var b=e[a],c=b.length;--c+1;)b[c]===d&&b.splice(c,1)}}})(window);

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.