Friday, October 18, 2013

jQuery live is dead

the new live

So here's how I reintroduced $.live to my jQuery.
Unfortunately, .on(action,selector,func) does not seem to understand anything but the most basic selectors, and that makes it much much worse than the old live, which could handle 

$('.module_container .core_data th.secondary').live('click',function(){});
This, as well as most complex selectors are now impossible to .live() it seems (or maybe my version of jQuery is full of bugs, it's called 1.10.1 or whatever).
    $ = function (action,func) {
        return this;

live vs on

You should still try and learn .on, which lets you put the delegation on any element rather than the document itself.
If your element has 0 static parent elements apart from body/html (i.e. it is dynamically added to the body or html), live is the correct approach (and having javascript create 99% of your html is the correct approach to the modern web application).
Otherwise, you should be using .on in order to make event handling lighter - the lookup for the handler can become slow if you add a zillion handlers on the same element, which is what happens when you use .live for everything.

event delegation is slow

The reason live and on are slow, is because when an event is delegated using the jQuery method, an event handler is created on the document (or your selector) that will check whether or not the bubbled event target matches the selector.
So what's actually slow is the selector itself, and the very long list of if(match(,selector)){callback1234();} which is bad design, whether you use "on" or "live".

the solution

If you still hit performance bottlenecks related to handler lookup, you should consider dynamically adding .on handlers to children elements (delegated event delegation), or go all the way and dynamically adding handlers to the elements you create (no event delegation).
It mostly depends on the percentage of events that are actually triggered and the number of different events that bubble up to the same delegated element, but you can have your answer with just profiling.
Actually, $(document).on or live both get you your handlers in every case. $(anything else).on will fail if it's not handled post load, i.e. packaged in a function and called on purpose in .ready().

the best solution

Drop jQuery. It takes 96KB to do mostly nothing. Write your own event delegation and enjoy a freedom that far surpasses both what .on() and .live() ever did.

Learn dynamic event delegation delegation ;) (it's called eventception)

No comments:

Post a Comment