How to translate jQuery.live () to .on () with events related to this?

I am in the process of converting code from an obsolete .live() API to .on() (see jQuery 1.7 release notes )

I have live events attached to this in several custom jQuery plugins, for example.

 this.live('click', function() { ... }); 

The jQuery.live () doc contains some recommendations on how to switch to .on() as follows:

 $(selector).live(events, data, handler); // jQuery 1.3+ $(document).on(events, selector, data, handler); // jQuery 1.7+ 

however this does not work:

 $(document).on('click', this, function() { ... }); 

so ... how do live events tied to this work with the new API on() ?

+15
javascript jquery
Nov 30 '11 at 10:22
source share
4 answers

Take a picture:

 $(document).on('click', this.selector, handler); 

The jQuery object has a selector property that represents the selector used to create this object.

Note that the selector is modified using workarounds, so I would suggest that your plugin is usually used when initially selecting the DOM.




To avoid using an internal property, you can simply change the API of your plugin so that it is explicitly passed.

+9
Nov 30 '11 at 10:24
source share

The .selector property is undocumented and is likely to be removed when .live () is removed. What did this code look like when using .live ()? How are these plugins used?

+3
Nov 30 '11 at 23:30
source share

As in jQuery 1.7, the on docs function is used to replace existing individual event binding methods:

one docs is a special case and you must continue to use it as is.

Existing events continue to exist and are simply aliases on . There is no official report that they will be deleted, so you can be safe to continue to use them if you understand them better. live and die are deprecated from jQuery 1.7, as mentioned in the blog post and on live docs .

The on event has several formats, but the signature of the function is as follows:

 .on( events [, selector] [, data], handler ) 

Bind:

 $(selector).bind(events, data, handler); $(selector).on(events, null, data, handler); 

Source:

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

Delegate:

 $(selector).delegate(subselector, events, data, handler); $(selector).on(events, subselector, data, handler); 

Source:

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

Live:

 $(selector).live(events, data, handler); $(document).on(events, selector, data, handler); 

Source:

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

Note that this.context was set using this.context = document; as indicated in $(document).on(...) .

+3
Dec 01 '11 at 14:33
source share
 $(selector).on(events, data, handler) 

Still works great. You can still use this. Check out .on docs

0
Dec 01
source share



All Articles