Created
October 25, 2012 13:35
-
-
Save MathRobin/3952579 to your computer and use it in GitHub Desktop.
Lightweight PubSub constructor
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(); | |
pubsub.subscribe("someEvent", function (message) { | |
console.log('Hello', messge); | |
}); | |
pubsub.publish("someEvent", "world"); | |
pubsub.unsubscribe("someEvent"); |
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
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. |
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
/** | |
* 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