BackboneJS Custom Events
This is a fiddle play with Views and sub Views implementing some custom events for mouse click!
by secretgspot
HTML
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap-responsive.css">
<!--
TwitterBootstrap Skeleton
-->
<div class="container">
<header class="page-header">
<h2>BackboneJS Custom Events - <small>Just play with events and custom events!</small></h2>
</header>
<p>
This fiddle play with custom events for views and sub-views.<br />
Try to <u>click</u>, <u>double-click</u> and <span class="label label-info">triple-click</span>on following paragraps!
</p>
<p>
Please startup your console to read event's log!
</p>
<hr />
<div id="app"></div>
<hr />
<h3>Follow Me!</h3>
<p>
Don't forget to <b>follow me on Twitter</b>: <a href="https://twitter.com/movableapp" target="_blank">@MovableAPP</a>
</p>
<p>
<a href="https://twitter.com/movableapp" class="twitter-follow-button" data-show-count="false">Follow @movableapp</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
</p>
</div>
JavaScript
var SectionView = Backbone.View.extend({
tagName: 'section',
/**
* Setup custom events just like "normal events".
*/
events: {
'custom_event' : 'onCustomEvent', // general custom event
'custom_click' : 'onClick', // single click custom event
'custom_dblclick' : 'onDblClick', // duble-click custom event
'custom_trplclick' : 'onTrplClick' // triple-click custom event
},
/**
* Then handle these kind of event like "normal events"!
*/
onCustomEvent: function( e, subView ) {
console.log("--------");
console.log("Custom Event");
console.log('event:');
console.log(e);
console.log('sub-view:');
console.log(subView);
console.log('context:');
console.log(this);
console.log("--------");
},
onClick: function( e, subView ) {
subView.highlight( '#eee' );
},
onDblClick: function( e, subView ) {
subView.highlight('yellow');
},
onTrplClick: function( e, subView ) {
subView.highlight( 'red' );
}
});
var ParaView = Backbone.View.extend({
tagName: 'p',
clickCounter: 0,
clickTimeout: null,
events: {
'click' : 'onClick'
},
initialize: function() { this.render() },
render: function() {
this.$el.html( this.options.content );
return this;
},
onClick: function( e ) {
e.stopPropagation();
this.clickCounter++;
// Timeouting to calculate how many click happened
clearTimeout(this.clickTimeout);
this.clickTimeout = setTimeout(_.bind(function(){
// General custom event
this.$el.trigger( 'custom_event', this );
// per click number...