Created
February 11, 2012 18:49
-
-
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).
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
/* 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); |
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
var pubsub = new PubSub(); | |
/* Subscribe */ | |
pubsub.subscribe('topic', fn); | |
/* Publish */ | |
pubsub.publish('topic', [arg1, arg2, ..., argN]); | |
/* Unsubscribe */ | |
pubsub.unsubscribe('topic', fn); |
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
// 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