Home >Web Front-end >JS Tutorial >Tips on using jQuery's new event binding mechanism on()_jquery
Browsing jQuery’s deprecated list today, I found live() and die() in it. I quickly took a look and found that starting from jQuery 1.7, jQuery has introduced a new event binding mechanism, on() and off( ) The two functions handle event binding uniformly. Because there were bind(), live(), delegate() and other methods to handle event binding before, jQuery decided to launch a new function to unify the event binding methods and replace the previous methods from the aspects of performance optimization and method unification. .
on(events,[selector],[data],fn)
events: One or more event types separated by spaces and an optional namespace, such as "click" or "keydown.myPlugin".
selector: A selector string for the descendants of the selector element that triggers the filter event. If the selector is null or omitted, the event is always fired when it reaches the selected element.
data: When an event is triggered, event.data must be passed to the event processing function.
fn: The function executed when the event is triggered. The false value can also be used as a shorthand for a function that returns false.
When the second parameter 'selector' is null, there is basically no difference in usage between on() and bind(), so we can think that on() just has one more option than bind() 'selector' parameter, so on() can easily replace bind()
Before 1.4, I believe everyone liked to use live() because it can bind events to current and future elements. Of course, after 1.4, delegate() can also do similar things. The principle of live() is very simple. It delegates events through the document, so we can also use on() to achieve the same effect as live() by binding the event to the document.
How to write live()
Replace delegate()
delegate() was introduced in 1.4 to delegate event binding issues of descendant elements through ancestor elements, to some extent Similar advantages to live(). It's just that live() is delegated through the document element, and delegate can be any ancestor node. The writing method of using on() to implement the proxy is basically the same as that of delegate().
How to write delegate()
Summary
jQuery launched on() for two purposes, one is to unify the interface, and the other is to improve performance, so use on() from now on Replace bind(), live(), delegate. In particular, don't use live() anymore, because it is already on the deprecated list and will be killed at any time. If you only bind the event once, then use one(), there is no change in this.