modern-web-design-and-development

(Brent) #1

delegate()


A shortfall of live() is that, unlike the vast majority of jQuery methods, it
cannot be used in chaining. That is, it must be used directly on a selector,
like so:


1 $('#myDiv a').live('mouseover', function() {

(^2) alert('hello');
3 });
But not...
1 $('#myDiv').children('a').live('mouseover', function() {
(^2) alert('hello');
3 });
... which will fail, as it will if you pass direct DOM elements, such as $
(document.body).
delegate(), which was developed as part of jQuery 1.4.2, goes some way
towards solving this problem by accepting as its first argument a context
within the selector. For example:
1 $('#myDiv').delegate('a', 'mouseover', function() {
(^2) alert('hello');
3 });
Like live(), delegate() binds events both to current and future
elements. Handlers are unbound via the undelegate() method.


Real-Life Example


For a real-life example, I want to stick with DOM-scripting, because this is
an important part of any RIA (Rich Internet Application) built in JavaScript.

Free download pdf