What happens when I bind an event handler to a DOM element and then subsequently destroy the DOM element? Do I have to go through a process of unbinding the event handlers?
<div id="el1">
<span id="c">Click Me!</span>
</div>
<span id="note">Note...</span>
<script>
var i=0;
$("#c").click(function(){
i++;
$("#note").html("'Click Me!' was clicked.");
$("#el1").html("<span id=\"c\">Click Me! ("+i+" time)</span>");
});
</script>
In Action: http://jsfiddle.net/lordloh/FyLdM/
Obviously, the even handler does not bind to the new DOM object with same id. The work around I am using is
<div id="el1">
<span id="c">Click Me!</span>
</div>
<span id="note">Note...</span>
<script>
var i=0;
$("#c").click(clickHandler);
function clickHandler(){
i++;
$("#note").html("'Click Me!' was clicked.");
$("#el1").html("<span id=\"c\">Click Me! ("+i+" time)</span>");
$("#c").click(clickHandler);
}
</script>
In Action: http://jsfiddle.net/lordloh/FyLdM/1/
What I am concerned about is whether this is a bad practice or is such a thing acceptable? What happens if this sequence is repeated millions of times? Could the javascript engine run the risk of running out of memory?