views:

23

answers:

1

I am about to clone a part of form which has some actions bound to click events. I want to change all occurences of word TEMPLATE in attributes to 'n_'+ID. I want to abstract from structure of cloned part - It would be one TEMPLATE or 10. I tried to something like this but the bindings are lost:

insert = function(){
    var old = $('#TEMPLATE');
    var copy = old.clone(true); 
    var html = old.html().replace(/TEMPLATE/g,'n'+next_ID);
    old.html(html);
    old.attr('id','n'+next_ID);
    old.show('fast');
    old.after(copy);
    next_ID++;
}

Is there any way to do it easily without knowing anything about the structure of the copied element.

+2  A: 

No. You would have to re-add handlers each time.

If you really want to avoid this, use event delegation (delegate() or live()) to attach your event handlers. That way they are not associated with particular node objects, but only the placement of elements, whether they match a selector, at event firing time.

$(myform).delegate('.dosomething', 'click', function() {
    // handle clicks on any .dosomething in the form now or added later
});

(And try to avoid text processing over the html()/innerHTML. This is unreliable. It's better to iterate over objects whose names or classes you want to change doing it with attr.)

bobince