Showing posts with label bind vs on jquery. Show all posts
Showing posts with label bind vs on jquery. Show all posts

Thursday 11 August 2016

Difference between on and bind in jQuery


The .bind() method registers the event and event handler directly to the DOM element.This method is still very handy when wiring-up event handlers, but there are various performance concerns as are listed below.
Internally .bind() maps to .on() as per current version of Jquery .bind may be removed from future versions at any time. There is no reason to keep using .bind and every reason to prefer .on instead.
The .bind() method will attach the event handler to all of the anchors that are matched! That is not good. Not only is that expensive to implicitly iterate over all of those items to attach an event handler, but it is also wasteful since it is the same event handler over and over again.

Problems
  1. The method attaches the same event handler to every matched element in the selection.
  2. It doesn’t work for elements added dynamically that matches the same selector.
  3. There are performance concerns when dealing with a large selection.
  4. The attachment is done upfront which can have performance issues on page load.
The on() method as 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.

Cons 1. Brings confusion because the behavior changes based on how you call the method.