TinyCore.js - Subscribe/UnSubscribe/Publish Events
by JuanMa Garrido
March 24, 2013
HTML
<script src="https://raw.github.com/mawrkus/tinycore/master/src/TinyCore.js"></script>
<div id="container">
<h3>Press buttons to see the messages in the "console"...</h3>
<ol>
<li><button id='subscribe'>Subscribe</button> → press button to subscribe 'my-module-listener' to <em>button:clicked</em></li>
<li><button id='unsubscribe'>Unsubscribe</button> → press button to unsubscribe 'my-module-listener' of <em>button:clicked</em></li>
<li><button id='notify'>Notify</button> → press button to Notify <em>button:clicked</em> from 'my-module-notifier'</li>
</ol>
</div>
<a href="#" id="clear_logs">[clear logs]</a>
<div id="logs"></div>
CSS
#container { padding:10px; font-family: Arial; }
#logs { height:500px; margin:20px 10px; padding:10px; font-family: Courier; font-size:11px; border:1px solid #000; overflow-y:scroll; }
em { font-family: Courier; font-size:13px; font-weight:bold; }
h3 { font-style: italic; margin-bottom:10px; }
#clear_logs { position: absolute; right: 9px; margin-top: -5px; }
JavaScript
function _log( sMsg, sColor ){
var oParag = document.createElement('p'),
oLogs = document.getElementById( 'logs' );
sColor ? oParag.style.color = sColor : null;
oParag.innerHTML = sMsg;
oLogs.appendChild(oParag);
oLogs.scrollTop = oLogs.scrollHeight;
};
$("#clear_logs").click ( function () {
$("#logs").html("");
});
TinyCore.Module.register("my-module-listener", function ( oSandBox ) {
return {
onStart: function () {
$("#subscribe").click( this.subscribeClick );
$("#unsubscribe").click( this.unsubscribeClick );
},
subscribeClick : function() {
_log ( new Date(), "blue" );
_log ("Module 'my-module-listener' Started", "green");
oSandBox.subscribe( ['button:clicked'], this.log_msg_topic );
_log ("listening to Topic [button:clicked]" , "red");
_log ("<br/>");
},
unsubscribeClick : function() {
_log ( new Date(), "blue" );
_log ("Module 'my-module-listener' Started", "green");
oSandBox.unSubscribe( ['button:clicked']);
_log ("NOT listening to Topic [button:clicked] anymore" , "red");
_log ("<br/>");
},
log_msg_topic : function (oTopic) {
var sTopicName = oTopic.name,
oData = oTopic.data;
_log( new Date(), "blue" );
_log("module: 'my-module-listener'", "orange");
_log("handler: 'log_msg_topic'", "green");
_log('Topic [button:clicked] received...','red');
oData && oData.msg ? _log ("msg: " + oData.msg) : null;
_log("<br/>");
}
};
});
TinyCore.Module.register("my-module-notifier", function ( oSandBox ) {
var _MSG = "Now that we know who you are, I know who I am. I'm not a mistake! It all makes sense! In a comic, you know how you can tell who the arch-villain's going to be? He's the exact opposite of the hero. And most times they're friends,...