caramba caramba - 4 years ago 358
Javascript Question

Window remove eventListener resize function

Having a function doing some things on window load or resize. As soon as something happend I don't need the

window.resize
event listener any more so I tried to remove the
resize event listener
but I don't get it to work.

Code below is same as in this jsFiddle (you need to resize window so not really possible on stackoverflow code snippet)



blubb = function(element) {
this.element = element;

this.blubber = function() {

document.querySelector('.data').innerHTML = window.innerWidth + 'px';

if(window.innerWidth < 800) {
this.element.style.backgroundColor = 'orange';

// here remove EventListener
// is not working
window.removeEventListener('resize', (function() { this.blubber() }).bind(this));
} else {
this.element.style.backgroundColor = 'powderblue';
}
};

this.blubber();
window.addEventListener('resize', (function() { this.blubber() }).bind(this));
};

blubb(
document.querySelector('.blubb')
);

.blubb {
width: 300px;
height: 300px;
background-color: powderblue;
}

<h1>Change visible area size and reload</h1>
<p>Should be once above 800px and once below 800px</p>
<div class="data"></div>
<div class="blubb"></div>





So if
div.blubb
once changed to orange I would like to remove the event listener which I've tried with:


window.removeEventListener('resize', (function() { this.blubber() }).bind(this));


But on resize I see the event is not removed. What am I doing wrong?

Answer Source

To remove event listener which where added using bind() you just have to store listener.bind(this) in a variable. Because bind() is creating a new reference each time its called.

So you could do something like this:

var myListener = function(event) { 
... 
};
var myListenerWithContext = myListener.bind(this);
element.addEventListener('event', myListenerWithContext);
element.removeEventListener('event', myListenerWithContext);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download