I have this function, to create a DIV on-the-fly. But now, I want to destroy this object on onclick event, but I just don't know how.
function creatediv(id) {
var newdiv = document.createElement('div');
newdiv.setAttribute('id', id);
newdiv.onclick=function(){this=null;}; //bad function
document.body.appendChild(newdiv);
}
What am I missing?
Thanks
create(baseObject); myObject. init = function() { /* do some stuff... */ delete this; }; myObject. init();
The destroy() method of the client object explicitly destroys that instance of the object and all its associated properties. If this method is not called, the JavaScript runtime will destroy the object after 10 minutes or after the time specified with the client.
Just setting it null will not destroy it. You need to remove it from the document tree while making sure there are no references pointing to it.
function creatediv(id) {
var newdiv = document.createElement('div');
newdiv.setAttribute('id', id);
newdiv.onclick=function(e) {
this.parentNode.removeChild(this);
};
document.body.appendChild(newdiv);
newdiv = null;//required in IE to prevent memory leak
}
The accepted answer seems wrong to me. First, it doesn't consider newdiv containing childnodes, so the suggested remove routine maintains a danger for memory leaks via closures (IE). Second, because of the position of 'newdiv = null' the creatediv function immediately destroys the just created element. I would recommend using Douglas Crockfords purge function for the click handler, substituting d with this.
function purge(d) {
var a = d.attributes, i, l, n;
if (a) {
l = a.length;
for (i = 0; i < l; i += 1) {
n = a[i].name;
if (typeof d[n] === 'function') {
d[n] = null;
}
}
}
a = d.childNodes;
if (a) {
l = a.length;
for (i = 0; i < l; i += 1) {
purge(d.childNodes[i]);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With