javascript

jQuery don’t use Bind, Live or Delegate

jQuery Bind:

Attach a handler to an event for the elements.

How to use:

$('button').bind('click', function() {
alert('User clicked on "button."');
});

jQuery Live:

Attach an event handler for all elements which match the current selector, now and in the future.

How to use:

$('button').bind('click', function() {
alert('User clicked on "button."');
});

jQuery Delegate:

Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.

How to use:

$("a").delegate("span", "click", function(){
$(this).toggleClass("chosen");
});

So why you shouldn’t use jQuery Bind, Live or Delegate?

Starting from jQuery 1.7.1, jQuery presented a new way to handle bind, live and delegate events. it’s a Method called on();

jQuery on()

Attach an event handler function for one or more events to the selected elements.

Behind the scene:

when you bind an event in the DOM, jquery call this function to process this event:

bind: function( types, data, fn ) {
   return this.on( types, null, data, fn );
}

same thing for live & delegate:

live: function( types, data, fn ) {
    jQuery( this.context ).on( types, this.selector, data, fn );
    return this;
},
delegate: function( selector, types, data, fn ) {
    return this.on( types, selector, data, fn );
}

The way it should be now:

$("button").on("click", function(event){
    alert($(this).text());
});

Hope this can help you folks!

Thanks,
Mohamed Alaa

Discussion

No comments for “jQuery don’t use Bind, Live or Delegate”

Post a comment

You must be logged in to post a comment.