Search code examples
jquerylivequery

jQuery & livequery - check if a function has been attached to a element


I'm running this:

$("*:not(#boo) .content").livequery(function(){  
  $("input, select").blah();
});

blah() looks like this:

(function( $ ) {
  $.fn.blah = function(){
    var that = this;
    return this.each(function(){
       $(this).bind('change', function(){
           // do some stuff here

           return true;
        }).change();

   });
 };

})(jQuery);

and the html looks like:

<div id="boo">
 <div class="content">
  <input type="text" />
  <input type="text" />
  ...
 </div>
</div>

<div class="content">    
 <input type="text" />
 <input type="text" />
</div>
...

so what I'm trying to do is to attach that function & event to every input element that is not inside #boo. This works, but the problem is that is doing it like every second over and over again and the browser freezes.

I need livequery because the html gets updated sometimes, and I need to attach the event again to new elements.

So how can I check if blah() has already been applied to a input element and stop there ?


Solution

  • When you query $.data( object, 'events' ) you get an object back with properties of the events attached to it. So in your case you could add this conditional:

    (function( $ ) {
      $.fn.blah = function(){
        var that = this;
        return this.each(function(){
           if ($.data( $(this).get(0), 'events' ) !== void(0) &&
               $.data( $(this).get(0), 'events' ).change === void(0)) {
               $(this).bind('change', function(){
                   // do some stuff here
                   return true;
               }).change();
           }
       });
     };
    })(jQuery);
    

    ...in order to only bind the function if it hasn't been already.