Kanji listeners/notify sample
by tnhu
HTML
<script src="https://dl.dropboxusercontent.com/u/7677927/kanji/lib/jquery.min.js"></script>
<script src="https://dl.dropboxusercontent.com/u/7677927/kanji/lib/jsface.js"></script>
<script src="https://dl.dropboxusercontent.com/u/7677927/kanji/lib/jsface.ready.js"></script>
<script src="https://dl.dropboxusercontent.com/u/7677927/kanji/kanji.js"></script>
<!-- Two red namespace Timer components -->
<script data-com="Timer/red" data-cfg="{ 'src': 'Red Sender 1' }"></script>
<script data-com="Timer/red" data-cfg="{ 'src': 'Red Sender 2' }"></script>
<!-- Blue and green namespace Timer components -->
<script data-com="Timer/blue" data-cfg="{ 'src': 'Blue Sender' }"></script>
<script data-com="Timer/green" data-cfg="{ 'src': 'Green Sender' }"></script>
<!-- Other Timer components without namespace -->
<script data-com="Timer" data-cfg="{ 'src': 'Sender1' }"></script>
<script data-com="Timer" data-cfg="{ 'src': 'Sender2' }"></script>
<script data-com="Timer" data-cfg="{ 'src': 'Sender3' }"></script>
<!-- Listener listens to all kinds of timer events -->
<script data-com="Listener"></script>
JavaScript
Class(Kanji, {
id: 'Timer',
lazy: false,
init: function(container, config) {
var th = this;
this.$body = $(document.body);
this.config = config;
this.counter = 0;
this.intervalId = setInterval(function() {
if (th.counter++ > 10) {
clearInterval(th.intervalId);
}
th.notify('time:up', +new Date(), config.src);
}, 4000);
},
/*
* when namespace is declared in a component (aka data-com="ComponentId/namespace'), sender must specify
* namespace with event id to route to the correct destination.
* For example Kanji.notify('time:show') notifies all Timer without namespace, Kanji.notify('time:show/red') notifies Red Timer
*/
listeners: {
'time:show': function() {
$('<p style="color: magenta;">Source:' + this.config.src + '</p>').appendTo(this.$body);
}
}
});
Class(Kanji, {
id: 'Listener',
type: 'shared',
lazy: false,
init: function() {
this.$body = $(document.body);
},
listeners: {
/**
* Listen to 'time:up' event on Sender with namespace 'red'
*/
'time:up/red': function(date, from) {
$('<p style="color: red;">Time:' + date + ' received from ' + from + '</p>').appendTo(this.$body);
// notify Red Timer to show its source
this.notify('time:show/red');
},
/**
* Listen to 'time:up' event on Sender with namespace 'green'
*/
'time:up/green': function(date, from) {
$('<p style="color: green;">Time:' + date + ' received from ' + from + '</p>').appendTo(this.$body);
},
/**
* Listen to 'time:up' event on Sender with namespace 'blue'
*/
'time:up/blue': function(date, from) {
$('<p style="color: blue;">Time:' + date + ' received from ' + from + '</p>').appendTo(this.$body);
},
/**
* Listen to 'time:up' event on other senders
*/
'time:up': function(date, from) {
$('<p>Time:' + date + ' received from ' + from + '</p>').appendTo(this.$body);
}
}
});