views:

62

answers:

2

edit: changing .ready() call per Matt's suggestion.

I use jQuery to configure some stuff like so:

$(function ()
{
     $('.myThing').each(function() {

         ... configure it ...

     });
});

My problem is when a new element gets added to the DOM after .ready() has been called. The configuration is not performed on those elements.

For simple things like binding a click event, .live() gets the job done. But for more complicated stuff I have not found a good solution.

Is there an event for when the DOM changes? Or more particularly when new elements are added to the DOM?

Edited: Tentative solution using livequery seems to be:

$(function ()
{
    $.fn.configureIt = function()
    {
        ... configure it ...
    }
});
$('.myThing').livequery(function () {
    $(this).configureIt ()
});

Edited again: livequery turned out not to be the solution. It searches the DOM for added or removed elements often. On a reasonably fast computer, running a moderate page, this is fine. On a slow computer, with a very large page, several livequeries and IE6, it has half-second lag every few seconds and longer lag on page load.

We concluded that making a shared 'common behaviors' catered to our laziness. Since our team has some moderate JavaScript people and some next-to-no JavaScript people and no JavaScript gurus, we wanted to define conventions for HTML markup and not touch these behaviors with each new page. This proved to not be possible given our JavaScript knowledge at the time.

The solution we came up with was that whenever we change the DOM with AJAX or dynamic content creation, we would an event:

$('.stuff').load(loadUrl, postData, function() {
    $(this).trigger('contentLoaded');
    // among other stuff
});

And then for any widget type thing, we rely on this convention.

$('*').live('contentLoaded', function() {
    $('.myThing', this).configureIt();
});

It's not ideal. Individual page makers need to know about the convention of triggering a custom event when they do things in their page (admittedly encapsulated in some shared utility functions) and widget makers need to rely on page makers using this convention, but in the end this is not that big of a problem since we work on a closed team and don't publish our applications externally.

A: 

You mentioned already exploring the .live() method, but you might also want to consider looking at .delegate(). I'm still reviewing the API for something of a better fit--but perhaps it will suffice where .live() falls short.

STW
+1  A: 

I've used the livequery plugin for just that purpose. It works for me, but if it doesn't in your case you might at least get some ideas of how it works from the source code.

Marek Karbarz
That seems to do the trick. Thanks!
Parched Squid