jQuery special events
A theoretical exercise http://benalman.com/news/2010/03/jquery-special-events/
by Ben Alman
HTML
<h1>
<a href="http://benalman.com/news/2010/03/jquery-special-events/" target="_top">jQuery special events</a>
» A theoretical exercise
</h1>
<div id="test">
<div id="foo"></div>
<div id="bar"></div>
</div>
<div id="log"></div>
CSS
body { font-family: Arial, Helvetica, sans-serif; font-size: 0.8em; }
h1 { font-weight: 700; font-family: "Gill Sans", "Gill Sans MT", Arial, Helvetica, sans-serif; }
h1, a { color: #913D00; }
a:hover { color: #FF7F00; }
h1 { font-size: 120%; margin-bottom: 0.6em; }
.intro { font-style: italic; margin-top: 0.5em; }
#log {
margin-top: 1em;
}
JavaScript
function log(){
$('#log').append([].join.call(arguments,', ')+'<br/>');
}
$(function(){
var a = function(){},
b = function(){};
$('#test div').bind( 'myevent', a );
log(1);
$('#test div').bind( 'myevent', b );
log(2);
$('#test div').unbind( 'myevent', a );
log(3);
$('#test div').unbind( 'myevent', b );
});
//////////////////////////////////////////////////
// THE FOLLOWING CODE IS TAKEN FROM THE EXAMPLE //
//////////////////////////////////////////////////
(function($){
// Special event definition.
$.event.special.myevent = {
add: function() {
var elem = $(this),
data = elem.data( 'myevent' );
if ( !data ) {
elem.data( 'myevent', data = { bound_count: 0 } );
// Simulated "setup" code here.
log( 'setup', '#' + this.id );
}
data.bound_count++;
},
remove: function() {
var elem = $(this),
data = elem.data( 'myevent' );
if ( --data.bound_count === 0 ) {
elem.removeData( 'myevent' );
// Simulated "teardown" code here.
log( 'teardown', '#' + this.id );
}
}
};
})(jQuery);