Move this topic
jQuery.live / jQuery.fn.live Discussion
Answered
- Need more info
- Working on it
- Answered
in Developing jQuery Core
•
11 years ago
Update (02/01):
Given the amount of attention that this post has received, it is probably beneficial to provide some sort of a general synopsis before I mark it as answered. This is definitely a polarizing topic, and the discussion really took on a life of its own.
The developers have all been very responsive to this issue, and have listened to the feedback posted here and in various other locations. I don't want to extend any promises that haven't been made by the core devs, so I won't expand any more than to say that relevant API changes are under consideration. For now, I think that this particular topic has served its purpose - thanks for the great feedback everyone.
Update(02/02):
Oops - spoke too soon. John has landed $().delegate: http://forum.jquery.com/topic/jquery-live-jquery-fn-live-discussion#14737000000680478
Original Post:
This is somewhat of a long-running discussion, but I just wanted to create a fresh "home" for a conversation about a jQuery.live implementation (in addition to jQuery.fn.live). I specifically want to see what the majority opinion of the developers and community are, since this discussion has previously been spread out all over the place.
For those not familiar with the topic, the general issue is whether or not querying for unnecessary elements when registering live events is an anti-pattern of sorts, and whether or not it is severe enough to warrant an addition to the API.
For a more detailed description, feel free to check out my feature enhancement ticket here:
http://dev.jquery.com/ticket/5877
...or this post by Zach Leatherman:
http://www.zachleat.com/web/2009/05/08/performance-caveat-with-jquery-selectors-and-live-events/
Pardon the following link-flooding, but I would like to demonstrate what I percieve to be a growing awareness, and potential concern, regarding the topic:
http://forum.jquery.com/topic/live-events
http://forum.jquery.com/topic/will-the-live-method-be-improved-in-1-4
http://forum.jquery.com/topic/selectors-in-live-method
http://forum.jquery.com/topic/live-types-of-events-number-of-events-and-more
http://dev.jquery.com/ticket/5425
http://github.com/furf/jquery-live
I have created a sample jQuery.live implementation that can be found here (including unit tests): http://github.com/jmar777/jquery/commit/4c5380066a7dcb893e07358ac4f04b591400dd01
Edit: For a good look at the other side of this discussion, see this well articulated post by Paul Irish: http://paulirish.com/2010/on-jquery-live/
3
Replies(38)
Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
I definitely agree that performing `.live` binding on a jQuery object can appear confusing to developers because the event isn't actually being bound to the selected elements. Since we are all trained to `$('.find_something').do_something();`, and this is somewhat inconsistent with that metaphor, I wonder what the reasoning was for creating `$.fn.live` in the first place, instead of just `$.live`.
- Ben
http://benalman.com/ - jQuery BBQ, doTimeout, hashchange event, Message Queuing, postMessage, replaceText, Star Wipe, Untils, unwrap, urlInternal.. and more!
Leave a comment on cowboy.ben's reply
Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
I understand that the standard live implementation throws away all the selected elements. However this code does not have to reside inside document ready. If all the live bindings are taken out of document ready list then I'm sure it will speed up things a little bit. Although admittedly it might still not be fast enough for certain applications.
Re: Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
It's true that if you have the option to run this before the DOM ready, you don't pay much of a penalty, but this isn't always an option (the script could get loaded/invoked 30 seconds later in response to some user action).
Regardless, even though performance is somewhat of a concern here, I think the more important issue is having an expressive/logical API. jQuery does this extremely well, and the code is largely "self documenting". The problem with jQuery.fn.live, IMO, is that querying for the elements just doesn't make sense if all you want to do is set up some event delegation. It may be cheap to do in most cases... but that doesn't make it "right".
Edit: formatting
Leave a comment on neeraj.singh's reply
Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
My ideal solution would be a $.live method that would work as follows:
$.live( selector , context ).click(...).mousein(...).bind(... , ...);
That is $.live behaving like $ except the jQuery object would be empty and a boolean property would be set so that redirection could be coded in "bind" (and some manipulation methods that could be harmful).
Re: Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
it would definitely be nice to see $.live return an object that has live enabled methods like .click and .bind but I have two problems with it.
1) it's super confusing. You're "live" code looks exactly like your non-live code.
2) It would make jQuery have two main objects. A regular jQuery collection and "live" collection. This seems like a huge change for jQuery for very little gain.
I would rather see something like:
$(context).delegate(selector, event[, data], function);
$(context).delegate(selector, {
click: function(){},
mouseover: function(){}
});
Leave a comment on aubourg.julian's reply
Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
I've written up a summary about this issue with $.live and $.fn.live:
http://paulirish.com/2010/on-jquery-live/
I think I successfully debunk the performance claim, but there remain issues that likely need clarification.
Re: Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
Thanks Paul - I've added a link to your post in the issue description. I'll make my response on your article.
Re: Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
I will continue to fight against $.live for the simple fact that it is the complete opposite of anything in the jQuery API (a single function taking in a selector (!) and returning who knows what). If it takes a selector/DOM element/etc. then it belongs in the main jQuery() method.
I also strongly disagree with Brandon and option #4 - it completely breaks the callback conventions of jQuery.
I also strongly disagree with Brandon and option #4 - it completely breaks the callback conventions of jQuery.
- $(context).live("div", "click", function(){
- // What is 'this'? According to the jQuery API it should be context
- // but you'll probably want 'div' - which makes no sense.
- });
Re: Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
Thanks for clarifying John - for obvious reasons I have a great deal of respect for your opinion. It certainly does feel a bit awkward to pass a selector to a $.live signature, but the alternative doesn't feel right to me either. I think $.data/$.contains provide some precedence for $.foo methods accepting DOM elements, but nothing for a selector.
In my mind, it seems to be a choice of either expanding the scope of a $.foo method, or making a break in $().foo convention. Is this an incorrect assertion? If not, would the plan be to restrict further $().foo methods from imposing such restrictions (with respect to chaining and set manipulation)?
Leave a comment on paulirish's reply
Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
Why $(selector).delegate(selector, event, func) is the best way:
1. The Live plugin was similar, but not the same thing as event delegation. It's confusing. Calling it delegate is much clearer.
2. The 'chaining' factor. $(".foo").delegate(selector, event, func).show() is much more clear where the 'action is' (on foo).
3. Performance. You want people listening as low on the dom as possible. With JMVC, until you get 100s of selector comparisons, walking up the parent list was still the most expensive thing. You are training people correctly.
4. Impossible to build 'plugins with'. $().live is pretty much impossible to make sharable plugins with. As the selector is on the DOM, you might be responding to events not in your widget's control.
People might not like $().delegate … but at least they will have to understand the principles of what is going on.
You're missing this post about it:
http://groups.google.com/group/jquery-dev/browse_thread/thread/e3bb36f8a9dae2b5/7e3bc980cd327a74
Re: Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
2. This isn't a concern - .live() is a replacement for .bind(), not for something else. $(".foo").live("click", fn).show() behaves the same as $(".foo").bind("click", fn).show().
3. This is why we limit the closest walking based upon the context of the jQuery set. Additionally we already bind to the context specified in the original jQuery() call - so even there we have less walking and event capturing.
4. That's not true - that's the whole purpose of event namespacing. .live("click.myplugin") then later on you can remove all the .myplugin events that you bound - very tidy, same as with bind.
3. This is why we limit the closest walking based upon the context of the jQuery set. Additionally we already bind to the context specified in the original jQuery() call - so even there we have less walking and event capturing.
4. That's not true - that's the whole purpose of event namespacing. .live("click.myplugin") then later on you can remove all the .myplugin events that you bound - very tidy, same as with bind.
Leave a comment on Guest's reply
Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
John, I'll point you to:
- + my comment on paul's page
- + the (non-tested and very hasty) patch that is there (#3, ie http://pastie.org/790043 ).
I respect your view on jQuery being the conduit for selector/context pairs. However it seems quite clear to me that we have *2* types of jQuery nodelist objects:
- + one for query results (let's call them "real" or "actual")
- + another for present/future nodes (let's call them "virtual"or "dynamic")
However, current implementation doesn't acknowledge that and tries & virtualizes a "real" nodelist as soon as you hit the $.fn.live method (effectively nullifying the interest of a query being carried on in the first place but, also, changing the semantic of *this* -- to my knowledge, the only method in all of jQuery to do so). Furthermore, like others pointed out, if you made some traversing before hitting $.fn.live, things can get quite funky.
The situation is also frustrating, because I can't understand why I have all these nice methods on top of bind and nothing on top of live whereas, basically, I wanna do the exact same kind of bindings on "dynamic" nodelist as I do with those "existing" ones resulting from a query.
If you take a step back, the ideal solution would be to specify if the nodelist is "dynamic" or not at creation: you set a flag on the jQuery object telling if it is virtual or not: that way, it's easy to redirect from bind to live and from unbind to die under the hoods while always (and only) using bind/unbind whatever the situation. You gain access to all bind derivatives for virtual nodelists: click(), hover(), etc...
My first reflexe to implement this idea was to add a third parameter to the jQuery signature but it appeared quite quickly to me that jQuery(selector, context, true) or jQuery(selector, context, false) was looking quite awkward and unnatural. So the idea came to have a function under jQuery that would have the same selector/context signature and would return a virtual nodelist (an interface compatible with the results of a query with the infamous virtual/live flag in). Maybe this new function could just be a redirect to a three parameters jQuery but this is all just some technical pinpointing imo.
It may not be perfect, the patch probably doesn't work as intended (not sure I understood the bind/one thingy properly, I never ever entered into event.js before), but in the end, I can/could have things like this:
- jQuery.dynamic(selector,context).click(func).hover(funcIn,funcOut);
Which looks and feels very jQueryish if you ask me and has much more flexibility than a simple $.fn.live().
Anyway, just my 2 cents, like we say, and sorry for my sure-to-be approximate english ;)
PS: Zoho's list item code is broken it seems
Re: Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
I set up a little demonstration here which uses the $.dynamic() approach I was talking about. Just click the button, mouse over the divs and click to remove them. This is all live done using $.click() and $.hover().
Minified version of the plugin is 330 bytes. Full text version is here .
Toy with it and tell me what you think (knowing it hasn't been heavily tested and must have some pretty big holes).
Re: Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
Thank you for taking an interest in this question, Julian. I would like to try and scope the discussion a little, however, and focus less on the implementation of a potential replacement/fix for now. The most productive line of discussion right now is addressing the merits or shortcomings of the current $.fn.live implementation.
If it is decided that a fix/enhancement is warranted, it would then certainly be beneficial to examine several of the existing solutions (including yours) that have been suggested. Thanks again for jumping in, and please don't take this as a softly-worded "shut up". This conversation is just starting to get ahead of itself, especially considering that there are some key individuals who are not yet on board with the general premise.
Re: Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
Jeremy,
It is a softly-worded and very condescendant "shut up". This is a dev forum and you seem to have remembered it when you proposed your own patch right away in the introductory post of this very thread.
I think a sample page with some code in is worth a million words, so do you apparentely. I just hope you will check what I linked to before dismissing it as irrelevant since I checked your code before dismissing it as "yet another relocation of live that doesn't fix a thing".
Thanks you.
Re: Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
Julian - As you said, I did link to a patch in the original description, so that's a fair statement. My only intended point is that the cart seems to be getting ahead of the horse, and I'll accept blame for that as well. I honestly was not trying to remove you from the conversation, but rather shift focus. I'm sorry for any offense, it was unintended.
Leave a comment on aubourg.julian's reply
Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
I have always felt that "live" suffers from too much sugar. The recent changes for accurately binding to the context is certainly an improvement, but issues remain.
1. The context argument must be a DOM element and not a jquery collection (last time I checked). This can be confusing for new users of the framework.
2. Executing the selector against the DOM when there is no intent to actually use those elements seems wasteful and unnecessary.
3. In order to delegate events on multiple "contexts" you must repeat the "live" call multiple times.
For these reasons I completely avoid using "live" (but I love the "closest" method). Personally, I think the proposed "delegate" signature is quite useful, and can still utilize the current "live" implementation.
- $.each({ live:"listen", die:"unlisten" },function( live, listen ){
- $.fn[ listen ] = function( selector ){
- var args = ([]).slice.call( arguments, 1 );
- return this.each(function(){
- $.fn[ live].call({ selector:selector, context:this }, args );
- });
- };
- });
Leave a comment on mike.helgeson's reply
Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
$.live looks more unattractive the more and more you look at it
- $.live(selector,context,eventtype,data,handler);
Also you get into a LOT of problems if context is accepted as a string and data can continue to be any type.
John,
I think the primary purpose of this discussion is to examine how live() is NOT a replacement for bind(). It's not equivalent for a number of reasons, thus introducing cognitive inconsistency in how it _should_ work.
Secondly, the current API makes doing the *right* thing (providing a context for your live-binds) very ugly:
- $('.triggerbox a.trigger', $('#sidebar')[0]).live('click', ...
I don't know if 'delegate' is the right verb, but that API feels very suited to what's going on. As for your example above, I'd expect `this` to be the 'div' clicked on. It's a little different I agree, but it's understandably different.
Re: Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
It's hard to deny that $.live(selector[,context],eventType[,eventData],handler) is plain ugly. The more I look at the proposed solutions, the less I think my original patch is an appropriate fix. I suppose something like $.live({}) ($.ajax style) may still have some merit - it would at least be flexible for any number of convenience wrappers.
Regarding $().delegate, the only thing I don't care for is that it doesn't look close to anything in the current API... but it does seem to be the most expressive of the options. Excepting the one caveat about what "this" refers to, it would make the most sense to me as a new developer.
Re: Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
Re: Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
Jared - I haven't actually run any tests against your snippet, but looking at it, I love it. Makes a great deal of sense to me. No unnecessary work is done, and it feels like it actually belongs in the $.fn namespace.
I think it would be worth creating some unit tests for it. I can't speak on behalf of the devs, but if nothing else I would definitely say its plugin worthy.
Re: Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
Oops - just realized I left that last comment anonymously. That was me, btw.... :)
Leave a comment on paulirish's reply
Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
With regard to the performance implication of having to resolve the selector but not using that result - what if jQuery() was made to defer actually resolving a selector? Then, most methods would trigger the selector resolving, but something like "live" could just peek at what the selector is, instead. Example:
- $('li').live(click, handler);
I'm not sure how much complexity this would add to jQuery though, and whether it's worth it just for live (I can't think of any other jQuery.fn function that would need this sort of thing).
Re: Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
This subject is quite complex and can be confusing. I never managed to explain $().live() to some friends that know little of the DOM. This discussion (and Paul Irish's post) made clear to me why it's so difficult to advocate .live() to javascript newbies.
On the other hand I've been using delegation for years and when $().live() was first released it felt natural and so much simple to use then my previous delegation experience that even after seeing all it's flaws, I must say that I still like it very much.There is many proposals right now, I don't really like any of then, but if I was to choose one, I would stick with:
- $.live(selector,context,eventtype,data,handler);
@Ben, I'm afraid you're suggestion is impossible (someone correct me if I'm wrong). How could jQuery know that the DOM is or is not to be queryed? For instance:
- var collection = $('li'); // DOM must be queryed for collection[0] to work
Leave a comment on ben.hollis's reply
Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
For me the worst part of the current syntax aside from it being unintuitive to pass a context to the jquery selector rather than live() itself is the fact that only one descendent selector (to be "watched") can be registered at once. It happens extremely frequently that one desires to check for an event on a number of selectors beneath the ancestor node, not just one. Having to call .live() for each one makes for long and non-flowing code.
Here's a pastie of an example delegation plugin . delegate() takes 2 syntaxes, allowing for either a single or multiple selectors to be watched under the jquery selector.
Current required syntax:
Much better syntax. Note how it also happens to read in perfect English: "'ul#shapes' delegates 'click' event for 'li.square' elements".
The selector passed to the jQuery object should always, absolutely be the selector that determines which node(s) the event is registered on, not which descendent nodes are being monitored. Otherwise it ruins any legibility of the code. The emphasis should be the node that is doing the delegation, not the nodes which are being delegated for.
I think it's a mistake to move to $.live() if we're talking about a core method rather than a plugin. The jquery selector still makes sense. Not to mention that $.live(selector,context,...) is a horrible ordering of arguments, it should be $.live(context,selector,...) if this is the approach being taken.
Here's a pastie of an example delegation plugin . delegate() takes 2 syntaxes, allowing for either a single or multiple selectors to be watched under the jquery selector.
Current required syntax:
- var $shapes = $('ul#shapes');
- $('li.square', $shapes).live('click', function () { console.log('clicked square'); });
- $('li.circle', $shapes).live('click', function () { console.log('clicked circle'); });
Much better syntax. Note how it also happens to read in perfect English: "'ul#shapes' delegates 'click' event for 'li.square' elements".
- // single delegation
- $('ul#shapes').delegate('click', 'li.square', function () { console.log('clicked square'); });
- // multiple in one go
- $('ul#shapes').delegate('click', {
- 'li.square': function () { console.log('clicked square'); },
- 'li.circle': function () { console.log('clicked circle'); }
- });
The selector passed to the jQuery object should always, absolutely be the selector that determines which node(s) the event is registered on, not which descendent nodes are being monitored. Otherwise it ruins any legibility of the code. The emphasis should be the node that is doing the delegation, not the nodes which are being delegated for.
I think it's a mistake to move to $.live() if we're talking about a core method rather than a plugin. The jquery selector still makes sense. Not to mention that $.live(selector,context,...) is a horrible ordering of arguments, it should be $.live(context,selector,...) if this is the approach being taken.
Leave a comment on frickenate's reply
Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
I missed John's argument regarding callback conventions possibly causing confusion over what the expecation of $this within the event fn would be. I'm with Paul with regards to possibly overlooking this, as I'm not sure it's counter-intuitive at all.
What about this other important aspect: the simple fact is that .live() doesn't actually apply any functionality directly to the selector. $('li', $('ul')[0]) makes it look like something is actively being applied to 'li' selector, which is simply not true. The real action done here is on the context, not the selector (the event binding). How many other $.fn methods apply functionality to the context rather than the selector? The context is generally used to limit where the selector will match, not as a node to act upon. If I'm wrong with that statement, please do correct me.
What about this other important aspect: the simple fact is that .live() doesn't actually apply any functionality directly to the selector. $('li', $('ul')[0]) makes it look like something is actively being applied to 'li' selector, which is simply not true. The real action done here is on the context, not the selector (the event binding). How many other $.fn methods apply functionality to the context rather than the selector? The context is generally used to limit where the selector will match, not as a node to act upon. If I'm wrong with that statement, please do correct me.
Leave a comment on frickenate's reply
Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
Jared - I've just seen you're gist about this topic, nice work. But your internal live and die functions don't need the loop if you use jQuery 1.4.1 that already accepts multiple event types separated by space.
Leave a comment on irae.jquery's reply
Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
I've got to say that I find this most readable, and still very much in the jQuery style:
To me that naturally reads "In context, delegate click events on selector to callback, although "delegate" is not exactly the proper verb. A number of the suggestions have the first two parameters in the opposite order, but I can't find an easy way to parse that into readable English. Here "this" would be the element matching the selector. It's simple enough to imagine the implementation, and I can't see any likely performance issues.
- $(context).delegate('click', 'selector', callback)
To me that naturally reads "In context, delegate click events on selector to callback, although "delegate" is not exactly the proper verb. A number of the suggestions have the first two parameters in the opposite order, but I can't find an easy way to parse that into readable English. Here "this" would be the element matching the selector. It's simple enough to imagine the implementation, and I can't see any likely performance issues.
Re: Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
http://flesler.blogspot.com/2007/10/jquerylisten.html
i was using this for a long time until $.fn.live() was introduced. i found it quite intuitive and clear as to where in the DOM the handler/filtering is done, that way things like mousemove are sane to delegate.
i was using this for a long time until $.fn.live() was introduced. i found it quite intuitive and clear as to where in the DOM the handler/filtering is done, that way things like mousemove are sane to delegate.
Leave a comment on scott.sauyet's reply
Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
Leeoniya, that's exactly the same syntax, except that perhaps "listen" is better than "delegate".
+1
But wow, that's a lot more code than I thought it should be! I guess I'm missing something, because I thought it should be implementable with something like (modulo better error checking):
-- Scott
+1
But wow, that's a lot more code than I thought it should be! I guess I'm missing something, because I thought it should be implementable with something like (modulo better error checking):
- jQuery.fn.listen = function(event, selector, fn) {
- return $(this).each(function() {$(this).bind(event, function(evt) {
- if (evt && evt.target && $(evt.target).is(selector)) {
- fn.call(evt.target, evt);
- }
- });});
- };
-- Scott
Re: Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
if i'm not mistaken, $.fn.live() was just finally implemented shortly after Ariel joined the jQuery team....i was hoping that they would use his syntax which makes a lot more sense, and actually requested it back then, but it didnt happen.
i really dont think it is that great an expectation to force programmers to always pick a context instead of using document always. if you're using deletion, you should already have an idea of what's going on and why you need it in the first place.
without knowing how live() works many users will mistakenly replace it for one-off things that really should be coded using bind()...because live() without a context looks like a magical cureall for every case, and it's not.
i guess for heavy delegation the alternative isnt too terrible anyhow. eg use is() inside a regular .bind('mousemove'), but many wont know that distinction because it is hidden away.
i really dont think it is that great an expectation to force programmers to always pick a context instead of using document always. if you're using deletion, you should already have an idea of what's going on and why you need it in the first place.
without knowing how live() works many users will mistakenly replace it for one-off things that really should be coded using bind()...because live() without a context looks like a magical cureall for every case, and it's not.
i guess for heavy delegation the alternative isnt too terrible anyhow. eg use is() inside a regular .bind('mousemove'), but many wont know that distinction because it is hidden away.
Leave a comment on scott.sauyet's reply
Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
I knew that code was too simple! It won't handle events on child elements of the targeted ones. But a fix is not too hard:
- $.fn.listen = function(event, selector, fn) {
- return $(this).each(function() {
- var $context = $(this);
- $context.bind(event, function(evt) {
- if (evt && evt.target) {
- var $element = $(evt.target).closest(selector, $context);
- if ($element.length) {
- return fn.call($element[0], evt);
- }
- }
- });
- });
- };
Leave a comment on scott.sauyet's reply
Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
The only "problem" I have with the current implementation is the overhead cause by the selector if you're only performing a live binding. But that can be easily handled.
It follows the jQuery pattern perfectly. It is easy to read; "To any buttons within the toolbar, bind a click handler that does...". We don't really need to know where the binding actually occurs, we care about the buttons, not the toolbar. The this keyword refers to what we expect, the button clicked. If the toolbar is removed, so are the buttons - we lose the bindings. I don't see what's hard to understand here. We can avoid performance issues by using a context, which we should do anyway. And we can chain just like we're used to.
If there is any anti-pattern going around, the current implementation is not it. It's these suggestions. It's been interesting to read however!
- $(".button",toolbar[0]).live("click",function(e){});
It follows the jQuery pattern perfectly. It is easy to read; "To any buttons within the toolbar, bind a click handler that does...". We don't really need to know where the binding actually occurs, we care about the buttons, not the toolbar. The this keyword refers to what we expect, the button clicked. If the toolbar is removed, so are the buttons - we lose the bindings. I don't see what's hard to understand here. We can avoid performance issues by using a context, which we should do anyway. And we can chain just like we're used to.
If there is any anti-pattern going around, the current implementation is not it. It's these suggestions. It's been interesting to read however!
Leave a comment on anybakk's reply
Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
Based upon this discussion (and follow-up discussion on IRC) I've implemented and landed .delegate()/.undelegate():
http://github.com/jquery/jquery/commit/31432e048f879b93ffa44c39d6f5989ab2620bd8
Ticket: http://dev.jquery.com/ticket/6005
http://github.com/jquery/jquery/commit/31432e048f879b93ffa44c39d6f5989ab2620bd8
Ticket: http://dev.jquery.com/ticket/6005
Re: Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
Great! This is exactly what I wanted!
Thanks John!
Thanks John!
Re: Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
Will $.fn.live become deprecated in the next release, and eventually removed altogether? As it stands, there are now 2 ways to do the exact same thing, with one version simply being less intuitive and less efficient. Trying to explain why one should use $.fn.delegate over $.fn.live will now be a nightmare.
- $('li').live('click', fn); // deprecate this
- $(document).delegate('li', 'click', fn); // in favour of this
- // most people who write a line like this aren't actually wanting to
- // be able to add a new ul#shapes to the document, but rather want
- // to be able to add/remove child <li> elements.
- $('ul#shapes li').live('click', fn);
- // more efficient to attach the event to the <ul>
- $('ul#shapes').delegate('li', 'click', fn);
- // and if the user really *does* expect an appended ul#shapes to work
- $(document).delegate('ul#shapes li', 'click', fn);
Re: Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
.live() is absolutely not being deprecated - and I strongly disagree with your points. .live() exists as a drop-in replacement for the vast majority of cases where the bind method would be used - at little additional overhead and no additional API concerns.
We can certainly start to educate users as to when using delegate is appropriate and the benefits of binding to a lower part of the tree (note: this has NOT changed at all - we've always encouraged this, this is why .live() has supported specifying a context - all delegate is doing is making the specifying of that context simpler).
As always, jQuery optimizes for the most common case and that provides the simplest API. We've done that with .live() and feel as if we've done so with delegate as well.
We can certainly start to educate users as to when using delegate is appropriate and the benefits of binding to a lower part of the tree (note: this has NOT changed at all - we've always encouraged this, this is why .live() has supported specifying a context - all delegate is doing is making the specifying of that context simpler).
As always, jQuery optimizes for the most common case and that provides the simplest API. We've done that with .live() and feel as if we've done so with delegate as well.
Leave a comment on jeresig's reply
Re: jQuery.live / jQuery.fn.live Discussion
11 years ago
This whole issue over live() querying for unnecessary elements bugs me too. Although I'm seeing some solutions leaning in this direction, I don't think I've seen what seems like the straightforward one: Create a dummy jQuery object, then add a selector and context to it.
- // Tiny jQuery plugin
- $.dummy = function (selector, context) {
- var dummy = $();
- dummy.selector = selector || document;
- dummy.context = context || document;
- return dummy;
- };
- ...
- // No querying for unnecessary elements here!
- $.dummy(".someSelector").live("click", function () { // do stuff });
I've been using something similar to this for the last couple months. Hope I'm not missing something silly...
Leave a comment on etotheix's reply
Change topic type
Link this topic
Provide the permalink of a topic that is related to this topic
Reply to jmar777's question
{"z2877445":[14737000000680498],"z943863":[14737000000674067,14737000000675069],"z101630":[14737000000680765],"z3051593":[14737000000676614],"z2950936":[14737000000660717,14737000000673863],"z2878318":[14737000000659663],"z2951555":[14737000000673910,14737000000675004,14737000000674434],"z3044180":[14737000000658891,14737000000661082,14737000000691030],"z2950782":[14737000000653170],"z2566198":[14737000000658075,14737000000658071,14737000000680478,14737000000690972],"z426497":[14737000000660082,14737000000659790],"z2950332":[14737000000659798],"z2951850":[14737000000656023,14737000000658098,14737000000658170],"z2951053":[14737000000654148],"z899369":[14737000000653121,14737000000656001,14737000000659168,14737000000659278,14737000000660227,14737000000660555,14737000000664012,14737000000673711],"z2951341":[14737000000667642,14737000000667698],"z-1":[14737000000660092,14737000000658319,14737000000668464]}
Statistics
- 38 Replies
- 58845 Views
- 4 Followers