Difference between .delegate() and .live()
So I was looking at the jQuery source and I found this:
delegate: function( selector, types, data, fn ) {
return this.live( types, data, fn, selector );
},
So .delegate()
function is pretty much just the .live()
function. The only difference is the order of the arguments! Why would the jQuery people do such a thing?开发者_如何转开发
People generally omit the selector
parameter on live
, I'd bet most people don't even know the selector parameter is there.
delegate()
gives you easy access to the selector
parameter, which allows you to 'scope' your event listener to just a subset of the whole dom, which can result in better performance.
It's awkward to provide additional parameters after passing an inline anonymous function. Since the selector parameter is so useful, it makes sense for jquery to create a more convenient form.
See: http://www.alfajango.com/blog/the-difference-between-jquerys-bind-live-and-delegate/
They are exactly the same except:
.delegate()
lets you narrow down event handling on a certain element, while .live() must process events in the entire page because `live attaches the event handler at the document level..live()
takes advantage of the event bubbling from element until the document where asdelegate
stops at the element on whichdelegate
is applied.- Using
delegate
you have a very good control on the event handling as compared tolive
A general answer to grasp the fundamental idea is summarized at https://www.alfajango.com/blog/the-difference-between-jquerys-bind-live-and-delegate/:
The jQuery team have announced in v1.7 a new method for binding events called on. This method combines the functionality of live, bind, and delegate described below, allowing you to specify the binding method based the arguments passed rather than by using different function names.
精彩评论