Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.delegate() vs .on()

Tags:

jquery

I'm using jQuery in my web application. I've been using .bind() but I see that it is a little slow, so while reading the documentation I read about .on() and .delegate(). I understand how .delegate() works but I’m not clear on what is the difference between it and .on() or which is better in which scenarios.

Also I'm using jQuery 1.6 so I would like to know if it is worth it to prepare my script for jQuery 1.7 by putting in a condition similar to the following:

if(typeof $(selector).on == 'function'){     /* use .on() */ }else{     /* use .delegate() */ } 

Is this a good idea (to prepare for .on()) or is it just looking for trouble for nothing?

Please help me to get clear understanding of these methods.

like image 838
Galled Avatar asked Dec 02 '11 16:12

Galled


2 Answers

The .on() syntax is the new syntax that version 1.7 uses and it is meant to substitute .bind(), .delegate() and .live().

More here -> http://blog.jquery.com/2011/11/03/jquery-1-7-released/

New Event APIs: .on() and .off()

The new .on() and .off() APIs unify all the ways of attaching events to a document in jQuery — and they’re shorter to type!

  $(elements).on( events [, selector] [, data] , handler );   $(elements).off( [ events ] [, selector] [, handler] ); 

When a selector is provided, .on() is similar to .delegate() in that it attaches a delegated event handler, filtered by the selector. When the selector is omitted or null the call is like .bind(). There is one ambiguous case: If the data argument is a string, you must provide either a selector string or null so that the data isn’t mistaken as a selector. Pass an object for data and you’ll never have to worry about special cases.

All the existing event binding methods (and their corresponding unbinding methods) are still there in 1.7, but we recommend that you use .on() for any new jQuery project where you know version 1.7 or higher is in use. (emphasis mine)

like image 149
lalibi Avatar answered Oct 06 '22 00:10

lalibi


I recently answered a related question about this very topic.

The important part is:

The new ondocs function is used to replace the existing separate methods of binding events:

The existing events continue to exist, and are simply aliases of on. There is no official report to suggest that they will be removed, so you'd be safe to continue to use them if you understand them better.

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 ); } 

tl;dr

If you want backwards compatibility, just keep using .delegate()docs, if your code relies on newer jQuery features, feel free to use on.

like image 21
zzzzBov Avatar answered Oct 05 '22 23:10

zzzzBov