Skip to content

Instantly share code, notes, and snippets.

@elijahmanor
Created February 6, 2012 04:51
Show Gist options
  • Save elijahmanor/1749717 to your computer and use it in GitHub Desktop.
Save elijahmanor/1749717 to your computer and use it in GitHub Desktop.
Differences Between jQuery .bind() vs .live() vs .delegate() vs .on() Methods
<ul id="members" data-role="listview" data-filter="true">
<!-- ... more list items ... -->
<li>
<a href="detail.html?id=10">
<h3>John Resig</h3>
<p><strong>jQuery Core Lead</strong></p>
<p>Boston, United States</p>
</a>
</li>
<!-- ... more list items ... -->
</ul>
/* The .bind() method attaches the event handler directly to the DOM
element in question ( "#members li a" ). The .click() method is
just a shorthand way to write the .bind() method. */
$( "#members li a" ).bind( "click", function( e ) {} );
$( "#members li a" ).click( function( e ) {} );
/* The .delegate() method behaves in a similar fashion to the .live()
method, but instead of attaching the event handler to the document,
you can choose where it is anchored ( "#members" ). The selector
and event information ( "li a" & "click" ) will be attached to the
"#members" element. */
$( "#members" ).delegate( "li a", "click", function( e ) {} );
// ... more code ...
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
},
die: function( types, fn ) {
jQuery( this.context ).off( types, this.selector || "**", fn );
return this;
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
return arguments.length == 1 ?
this.off( selector, "**" ) :
this.off( types, selector, fn );
},
// ... more code ...
/* The .live() method attaches the event handler to the root level
document along with the associated selector and event information
( "#members li a" & "click" ) */
$( "#members li a" ).live( "click", function( e ) {} );
/* The jQuery .bind(), .live(), and .delegate() methods are just one
line pass throughs to the new jQuery 1.7 .on() method */
// Bind
$( "#members li a" ).on( "click", function( e ) {} );
$( "#members li a" ).bind( "click", function( e ) {} );
// Live
$( document ).on( "click", "#members li a", function( e ) {} );
$( "#members li a" ).live( "click", function( e ) {} );
// Delegate
$( "#members" ).on( "click", "li a", function( e ) {} );
$( "#members" ).delegate( "li a", "click", function( e ) {} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment