Hydra.js - Subscribe/Publish Events
HTML
<script src="https://github.com/tcorral/Hydra.js/raw/master/src/Hydra.js"></script>
<div id="container">
<h3>Press buttons to see the messages in the "console"...</h3>
<ol>
<li><button id='notify'>Notify</button> → press button to Notify <em>[my-channel]link:clicked</em></li>
<li><button id='listen'>Listen</button> → press button to Listen <em>[my-channel]link:clicked</em> from another module</li>
<li><button id='another_notify'>Notify</button> → press button to Notify <em>[my-channel]link:clicked</em> from another module</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
/* ----------------------------------------------------------- */
// HELPERS to log results
var oLogs = document.getElementById( 'logs' );
function logIt ( sMsg, sColor ){
var oParag = document.createElement('p');
sColor ? oParag.style.color = sColor : null;
oParag.innerHTML = sMsg;
oLogs.appendChild(oParag);
oLogs.scrollTop = oLogs.scrollHeight;
}
$("#clear_logs").click ( function () {
$(oLogs).html("");
});
/* ----------------------------------------------------------- */
/**
Module : my-module-listener-notifier
*/
Hydra.module.register("my-module-listener-notifier", function (bus) {
return {
events:{
'my-channel': {
'link:clicked':function ( oData ) {
logIt ( new Date(), "blue" );
logIt ("module: " + this.__module_id__, "orange");
logIt ("instance: " + this.__instance_id__ , "orange");
logIt ('Handler --> [my-channel] link:clicked', "green");
oData && oData.msg ? logIt ("msg: " + oData.msg) : null;
logIt ("<br/>");
}
}
},
init: function () {
logIt ( new Date(), "blue" );
logIt ("Module Started", "green");
logIt ("module: " + this.__module_id__, "orange");
logIt ("instance: " + this.__instance_id__, "orange");
logIt ("listening to... [my-channel] link:clicked" , "red");
logIt ("<br/>");
this.createLinkAndAddEvent();
},
createLinkAndAddEvent: function()
{
var self = this;
$("#notify").click(function () {
logIt ( new Date(), "blue" );
logIt ("module: " + self.__module_id__, "orange");
logIt ("instance: " + self.__instance_id__, "orange");
logIt ("notifying... [my-channel] link:clicked" , "red");
logIt ("<br/>");
...