Skip to content

Instantly share code, notes, and snippets.

@pjeweb
Created February 11, 2012 18:49
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 pjeweb/1803528 to your computer and use it in GitHub Desktop.
Save pjeweb/1803528 to your computer and use it in GitHub Desktop.
Simple PubSub snippet for both browser and nodejs (just remove outer wrap-function).
/* 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);
var pubsub = new PubSub();
/* Subscribe */
pubsub.subscribe('topic', fn);
/* Publish */
pubsub.publish('topic', [arg1, arg2, ..., argN]);
/* Unsubscribe */
pubsub.unsubscribe('topic', fn);
// 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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment