Sorting and reinserting elements removes bound functions
I need to sort so开发者_JAVA百科me rows after they've been inserted. What I'm doing now is:
var $r = $tbody.find('tr').sort(function(a,b) {
return compare(taxstatusOf(a), taxstatusOf(b));
});
$tbody.empty().append($r);
This works, except that functions that were bound to elements contained in the rows are no longer bound (or no longer fire, which amounts to the same thing).
So, is there a right way to sort rows that doing fail like this? Do I have to re-bind?
D'oh.
The right answer, sports fans, is .detach()
. .remove()
is supposed to strip the removed elements bare (removing local data and bound functions and such), which is great for garbage-collection and so forth but exactly what you don't want when you're planning to re-attach them later.
The working code:
var $r = $tbody.find('tr').sort(function(a,b) {
return compare(taxstatusOf(a), taxstatusOf(b));
}).detach().appendTo($tbody);
(I'm not going to "accept" my own answer for a little while in case someone comes up with a better one.)
(I guess it's good that I found the answer 30 seconds after posting the question. Now the next guy on SO will profit from my mistake.)
From the sample code you provide it looks like you're removing the original elements from the DOM and then re-adding them. As the newly-sorted elements weren't present in the DOM when the events were originally bound they have no events/functions bound to them.
To work around this, you could assign the original functions/events using live()
or delegate()
, which will bind to 'future,' as well as 'current,' elements; or you would indeed have to 're-bind' the events in your sorting code, obviously after the line $tbody.empty().append($r);
.
精彩评论