Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove event handler function from window?

Tags:

javascript

If I've added a function to the window object like this:

window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}

And lets say my code may run this snippet many times is there a danger in a memory leak? (since I never "delete" that function from the window [SPA])

And just to be on the safe side I prefer to remove that function when my component dies (angularjs2 by the way) how can I "unbind" a function from the window object?

I hope I understand right that each time I call window.onclick = function(...) I add a function and not replacing one

like image 850
kfir124 Avatar asked Jun 10 '16 15:06

kfir124


3 Answers

For a named function, use addEventListener and removeEventListener...

window.addEventListener('click', windowClickHandler, false);
window.removeEventListener('click', windowClickhandler, false);

You can have as many event listeners on an element, using the above method.

For unnamed functions, use...

window.onclick = function(event) { // do stuff; };
window.onclick = null;

You can only have ONE event handler set using the above method. Each window.onclick set using this method overwrites the previous one. Setting it to null simply removes the last one set.

It's up to each browser how it implements its garbage collection with regards to these calls.

like image 50
ManoDestra Avatar answered Nov 20 '22 07:11

ManoDestra


You cannot remove a specific anonymous event handler from an object when using the onEVENT syntax. Whenever you call object.onclick =, you overwrite whatever is currently assigned to the onclick property of object.

You will need to use addEventListener() and removeEventListener() with a named function:

function windowClicker(event) 
{
    if (event.target == modal) 
    {
        modal.style.display = "none";
    }
}

// Add the listener:
window.addEventListener('click', windowClicker, false);

// Remove it:
window.removeEventListener('click', windowClicker, false);
like image 25
BenM Avatar answered Nov 20 '22 09:11

BenM


If you add event like

window.onclick = function() {
    // some stuff..
}

Then there is only one onclick listener and you can remove it just like

window.onclick = undefined;

But if you want to remove named function then you can do something like this:

function abc(event) {
    // do something
}

window.addEventListener('click', abc); // add the listener

window.removeEventListener('click', abc); // remove the listener

And you can add multiple 'onclick' listeners like this, but you have to keep the reference to them, so anonymous functions are kept forever (till the page is reloaded).

like image 3
Azamantes Avatar answered Nov 20 '22 07:11

Azamantes