Skip to content

Instantly share code, notes, and snippets.

@MathRobin
Created October 25, 2012 13:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save MathRobin/3952579 to your computer and use it in GitHub Desktop.
Save MathRobin/3952579 to your computer and use it in GitHub Desktop.
Lightweight PubSub constructor
var pubsub = new Pubsub();
pubsub.subscribe("someEvent", function (message) {
console.log('Hello', messge);
});
pubsub.publish("someEvent", "world");
pubsub.unsubscribe("someEvent");
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Mathieu ROBIN <http://www.mathieurobin.com>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
/**
* Pub-Sub system, used for lightweight state machine
*
* @return {Object} Instance of Pubsub
* @constructor
*/
function Pubsub () {
"use strict";
var subscription_registry = {},
event = 0;
return {
/**
* Publish method
*
* @param channel
* @param message
*/
publish : function (channel, message) {
var placeholder;
for (placeholder in subscription_registry) {
if (subscription_registry.hasOwnProperty(placeholder)) {
if (placeholder.split('-')[0] === channel) {
subscription_registry[placeholder](message);
}
}
}
},
/**
* Subscription method
*
* @param channel
* @param callback method
*/
subscribe : function (channel, callback) {
subscription_registry[channel + --event] = callback;
},
/**
* Unsubscription method
*
* @param channel
*/
unsubscribe : function (channel) {
var placeholder;
for (placeholder in subscription_registry) {
if (subscription_registry.hasOwnProperty(placeholder)) {
if (placeholder.split('-')[0] === channel) {
delete subscription_registry[placeholder];
}
}
}
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment