Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the expression for live needs to be evaluated in jQuery

Tags:

jquery

The following question is inspired by this blog entry at ajaxian.com and this comment by paul irish.

Here is a way to declare live event.

$("li a").live(...)

As per this blog entry, it is my understanding that live events are nothing but a catch all at the document level. Any event that bubbles all the way to the top are caught by live events and if the selector is matching then the function is invoked.

It is my understanding that on document ready if I invoke

$("li a").live('click', ..)

then all jQuery should do is to put the literal selector 'li a' in memory somewhere. Now when a click happens and if that click bubbles all the way to the top then live should check what is the target element. If the target element satisfies the rule of 'li a' then the function should be fired otherwise ignored this bubbled up event.

Based on that presumption on document ready when I am calling

$("li a").live('click', ..)

then ideally jQuery should not actually go looking for all the element matching 'li a' because jquery does not do anything with those elements. I know for sure that the elements that are currently present in the document matching 'li a' are not bound to any event handler.

If all jQuery has to do is to put the literal 'li a' at the document root level then why go looking for elements matching the criteria 'li a' on document ready. But based on the comment link that I mentioned at the top, it seems jQuery actually goes about looking for element on document ready.

My question is why should live method find all the 'li a' methods when it is not going to do anything with them. I guess the live syntax should have been something like

$.live('li a', 'click', function(){})

Am I missing something here?

like image 844
Roger Avatar asked Nov 05 '09 14:11

Roger


2 Answers

My understanding of why it grabs all the elements from the DOM is because that is what the $() function does, then after it has selected the DOM elements it executes the function live().

In that case, you would need to use one of the workarounds suggested elsewhere in the answers here.

like image 198
Astra Avatar answered Oct 19 '22 23:10

Astra


i hacked around this issue by overriding find():

jQuery.fn.find = function(old) {
    return function() {
        var m = arguments[0].match(/^lazy:(.*)/);
        if(m) {
            this.selector = m[1];
            return this;
        }
        return old.apply(this, arguments);
    }
} (jQuery.fn.find);

  // this will select elements...
  $("input").live("click", function() {

  // this won't
  $("lazy:input").live("click", function() {
like image 26
user187291 Avatar answered Oct 19 '22 22:10

user187291