jQuery – .bind(), .live(), .delegate(), .on() ( and also .unbind(), .die(), .undelegate(), .off() )

jQuery - .bind(), .live(), .delegate(), .on(), .off(), .undelegate(), die(), .unbind()

All these functions are used to attach an event handler function to the selected elements or selectors. In this article I will take you through all the four set of functions to get an idea of what it is.

To start with, let me list down all the functions with short description and release details.

 

Method Short Description Added In Deprecated In Removed In
.bind() Attach a handler to an event for the elements. 1.0
.unbind()
Remove a previously-attached event handler from the elements.
1.0
.live() Attach an event handler for all elements which match the current selector, now and in the future. 1.3 1.7 1.9
.die() Remove event handlers previously attached using .live() from the elements. 1.3 1.7 1.9
.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. 1.4.2
.undelegate()
Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements.
1.4.2
.on()
Attach an event handler function for one or more events to the selected elements.
1.7
.off() Remove an event handler. 1.7

Which function to use? confused Confused, Which one to use, jQuery .bind(), .live(), .delegate(), .on() - Shemeer let’s go through the below details then you will be in a good position to decide which one to use and when.

.bind() and .unbind()

The .bind() method is used to register an events to existing html elements and .unbind() method is used to remove events, that are registered by .bind() method.

Syntax:-

 

Method Syntax Available from version
.bind() .bind( eventType [, eventData ], handler(eventObject) ) 1.0
.bind( eventType [, eventData ], preventBubble )
1.4.3
.bind( events ) 1.4
Parameter details are given below,

  • eventType:- A string containing one or more DOM event types, such as “click” or “submit,” or custom event names.
  • eventData:- An object containing data that will be passed to the event handler.
  • handler(eventObject):- A function to execute each time the event is triggered.
  • preventBubble:- Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true.
  • events:- An object containing one or more DOM event types and functions to execute for them.
.unbind() .unbind( [eventType ] [, handler(eventObject) ] ) 1.0
.unbind( eventType, false ) 1.4.3
.unbind( event )
1.4
Parameter details are given below,

  • eventType:- A string containing a JavaScript event type, such as click or submit.
  • handler(eventObject): The function that is to be no longer executed.
  • false: Unbinds the corresponding ‘return false’ function that was bound using .bind( eventType, false ).
  • event: A JavaScript event object as passed to an event handler.

Sample : –

Collapse | Copy Code
 $( document ).ready(function() {
  $( "#foo" ).bind( "click", function( event ) {
    alert( "The mouse cursor is at (" +
      event.pageX + ", " + event.pageY +
      ")" );
  });
});

The above code will cause a click on the element with ID foo to report the page coordinates of the mouse cursor at the time of the click.

Read more from http://api.jquery.com/bind/, http://api.jquery.com/unbind/

.live() and .die()

.live() method is used to add event handler to elements that are currently available in the page or dynamically added to the page whereas .die() is used to remove any handler that has been attached with .live().

Note: .live() and .die() are removed from jQuery version 1.9.

Method Syntax Available from version
.live() .live( events, handler(eventObject) ) 1.3
.live( events, data, handler(eventObject) )
1.4
.live( events ) 1.4.3
Parameter details are given below,

  • events:- A string containing a JavaScript event type, such as “click” or “keydown.” As of jQuery 1.4 the string can contain multiple, space-separated event types or custom event names. If events is the only parameter then events will be A plain object of one or more JavaScript event types and functions to execute for them.
  • data:- An object containing data that will be passed to the event handler.
  • handler(eventObject):- A function to execute each time the event is triggered.
.die() .die( eventType [, handler ] ) 1.3
.die() 1.4.1
.die( events )
1.4.3
Parameter details are given below,

  • eventType:- A string containing a JavaScript event type, such as click or keydown.
  • events:- A plain object of one or more event types, such as click or keydown and their corresponding functions that are no longer to be executed.

Sample:-

Collapse | Copy Code
<a class="link">Link Static</a>
<button id="addmore" type="button">Add more</button> 

 $(document).ready(function() {
   $('#addmore').click(function() {
      $('body').append(' <a class="link">Link Dynamic</a>');
        return false; 
  }); 
   $("a.link").bind('click', function() {
      alert('I am clicked');
   });
  });

As per the above code, when ever we click on the hyper-link (<a>) it will show an alert message.. We can add hyper-links dynamically using the button. but dynamically added links will not have click event attached. To make it work for both static control and dynamic we need to rewrite the code using live() as below,

Collapse | Copy Code
<a class="link">Link Static</a>
<button id="addmore" type="button">Add more</button> 

 $(document).ready(function() {
   $('#addmore').click(function() {
      $('body').append(' <a class="link">Link Dynamic</a>');
        return false; 
  }); 
   $("a.link").live('click', function() {
      alert('I am clicked');
   });
  });

Now all the static and dynamically created links will have the alert method event attached.

Read more from http://api.jquery.com/live/, http://api.jquery.com/die/

.delegate() and .undelegate()

.delegate() method behaves in a similar fashion to the .live() method, but the major difference is that It attaches the event handler to the context , rather than the document. The .undelegate() method is a way of removing event handlers that have been bound using .delegate().

Method Syntax Available from version
.delegate() .delegate( selector, eventType, handler(eventObject) ) 1.4.2
.delegate( selector, eventType, eventData, handler(eventObject) )
1.4.2
.delegate( selector, events ) 1.4.3
Parameter details are given below,

  • selector:- A selector to filter the elements that trigger the event.
  • eventType:- A string containing one or more space-separated JavaScript event types, such as “click” or “keydown,” or custom event names
  • eventData:- An object containing data that will be passed to the event handler.
  • handler(eventObject):- A function to execute each time the event is triggered.
  • events:- A plain object of one or more event types and functions to execute for them.
.undelegate() .undelegate() 1.4.2
.undelegate( selector, eventType ) 1.4.2
.undelegate( selector, eventType, handler(eventObject) )
1.4.2
.undelegate( selector, events ) 1.4.3
.undelegate( namespace ) 1.6
Parameter details are given below,

  • selector:- A selector which will be used to filter the event results.
  • eventType:- A string containing a JavaScript event type, such as “click” or “keydown”.
  • handler(eventObject):- A function to execute at the time the event is triggered.
  • events:- An object of one or more event types and previously bound functions to unbind from them.
  • namespace:- A string containing a namespace to unbind all events from.

Sample :-

Collapse | Copy Code
$( "table" ).delegate( "td", "click", function() {
  $( this ).toggleClass( "chosen" );
});

Read more from http://api.jquery.com/delegate/, http://api.jquery.com/undelegate/

.on() and .off()

The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. The .on() method provides all functionality required for attaching event handlers. The .off() method removes event handlers that were attached with .on().

Method Syntax Available from version
.on() .delegate( selector, eventType, handler(eventObject) ) 1.4.2
.delegate( selector, eventType, eventData, handler(eventObject) )
1.4.2
.delegate( selector, events ) 1.4.3
Parameter details are given below,

  • selector:- A selector to filter the elements that trigger the event.
  • eventType:- A string containing one or more space-separated JavaScript event types, such as “click” or “keydown,” or custom event names
  • eventData:- An object containing data that will be passed to the event handler.
  • handler(eventObject):- A function to execute each time the event is triggered.
  • events:- A plain object of one or more event types and functions to execute for them.
.off() .off( events [, selector ] [, handler(eventObject) ] ) 1.7
.off( events [, selector ] ) 1.7
Parameter details are given below,

  • selector:- A selector which should match the one originally passed to .on() when attaching event handlers.
  • events:- An object where the string keys represent one or more space-separated event types and optional namespaces, and the values represent handler functions previously attached for the event(s).

Sample:-

Collapse | Copy Code
$("p").on("click",function(){
  alert("The paragraph was clicked.");
});

The above code will be attaching the specified event to all (current and future) <p>.

Below code block is taken from jQuery 1.7.1.

You can see that for all the above listed methods the .on() method is being “overloaded” with different signatures, which in turn changes how the event binding is wired-up. The .on() method bring a lot of consistency to the API and hopefully makes things slightly less confusing.

Collapse | Copy 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 ...

Read more from http://api.jquery.com/on/, http://api.jquery.com/off/

Comparison

The .bind() method registers the type of event and an event handler directly to the DOM element. The .bind() doesn’t work for elements added dynamically that matches the same selector. This method is pretty easy and quick to wire-up event handlers. The shorthand methods like .click(), .hover(), etc make it even easier to wire-up event handlers. There is a performance issue while working with large selection as the method attaches the same event handler to every matched element in the selection.The attachment is done upfront which can have performance issues on page load.

The basic difference between .bind() and .live() is bind will not attach the event handler to those elements which are added/appended after DOM is loaded and there is only one event handler registered instead of the numerous event handlers that could have been registered with the .bind() method. When using .live() events always delegate all the way up to the document. This can affect performance if your DOM tree is deep. Chaining is not properly supported using .live() method. Using event.stopPropagation() is no longer helpful because the event has already delegated all the way up to the document. .live() method is deprecated as of jQuery 1.7 and removed from jQuery 1.9.

The .delegate() method is very powerful, The difference between .live() and .delegate() is, live function can’t be used in chaining. live function needs to be used directly on a selector/element. Also .delegate() works on dynamically added elements to the DOM where the selectors match. Chaining is supported correctly in .delegate().

The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers. Brings uniformity to the various event binding methods. but as the the way we call .on() method the behaviour also changes.

Note: If you are using jQuery 1.7+ then its advised to use .on() for attaching events to elements or selectors.

Conclusion

All the these jQuery functions are used to attach events to selectors or elements. Some methods performs better in some situations. If you are using jQuery 1.7+ then its advised to use .on() over all the event binding methods.

References

Summary

In this article I have given detailed explanation of jQuery methods that’s used for attaching/removing event handlers. I hope you have enjoyed this article and got some value addition to your knowledge.

from: http://www.codeproject.com/Articles/778374/JQUERY-JSON-and-Angular-Interview-questions

发表评论

电子邮件地址不会被公开。 必填项已用*标注