Skip to content

Instantly share code, notes, and snippets.

@remy
Created June 17, 2010 09:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save remy/441895 to your computer and use it in GitHub Desktop.
Save remy/441895 to your computer and use it in GitHub Desktop.
Experiment to see if .live can be replaced - no it shouldn't be
/********* DON'T USE THIS **************/
/**
* After thinking about it for a while, and as Kobi's comment says below
* this still has the wasteful selector which is one of the big reasons
* to use delegate in the first place - so please don't use this.
* - cheers, @rem
*/
(function ($) {
$.root = $(document); // hat tip: Cory Hart
// keep safe
$.fn._live = $.fn.live;
$.fn._die = $.fn.die;
$.fn.live = function (type, fn) {
$.root.delegate(this.selector, type, fn);
return this;
};
$.fn.die = function (type, fn) {
$.root.undelegate(this.selector, type, fn);
return this;
};
})(jQuery);
@KrofDrakula
Copy link

Where's $root defined? I only see $.root at the beginning.

@remy
Copy link
Author

remy commented Jun 17, 2010

@KrofDrakula - doh - cheers, typo there.

@kobi
Copy link

kobi commented Jun 17, 2010

The main benefit of delegate is that you don't run the selector through the DOM, eg .delegate('div', ... ) doesn't search for all Divs.
With this, you still call $('div'), so I'm not sure I get the point.
I might be missing other aspects of delegate though...

@sroucheray
Copy link

It appears that the delegate method uses live (line 2411 http://code.jquery.com/jquery-1.4.2.js) so you enter an infinite loop using delegate in a redefined live method.

@remy
Copy link
Author

remy commented Jun 17, 2010

@kobi - yeah, I just realised this a moment ago, the wasteful select is still happening so there's no point in replicating this at all. Much better just to do:

$(document).delegate('div', 'click', fn);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment