Often times I have elements hooked to added functionality, like:
$('.myfav').autocomplete();
$('.myfav').datepicker();
$('.myfav').click(somefunction);
But when more instances of this class are generated dynamically through some code, the new $('.myfav')
are dead and need rewiring, so I do this:
$("#somelink").click(function(){
//generate 10 new $('.myfav') and append them to the DOM
//re-wire them again as in the block above
$('.myfav').autocomplete();
$('.myfav').datepicker();
$('.myfav').click(somefunction);
});
What this means is that I end up having 2 identical blocks of code, 1 for the initial page load and one to rewire the new elements that get generated dynamically. This isn't DRY code and isn't very efficient.
Is this really the only way to get this done, or there another best practice? My gut tells me there's gotta be something more efficient than this (also to help DRY the code).
update
Looks like .live works well with .click as explained by cletus.
$('.myfav').live("click", somefunction);
But I tried it with custom-set plugins like .autocomplete and it didn't work. I tried this:
$('.myfav').live("click", autocomplete("somefile.php", {max: 15, mustMatch: true}));
So live doesn't look like it can handle these custom plugins (of course I could be wrong, please update if you know something)