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?
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);
do not use closure, just create a function, then use for both of add and remove event, something like this
var blubb = function(element) {
var evt;
this.blubber = function() {
// code...
if(window.innerWidth < 800) {
window.removeEventListener('resize', evt);
}
};
evt = this.blubber.bind(this);
window.addEventListener('resize', evt);
};
demo here: https://output.jsbin.com/vuyuvohure
code https://jsbin.com/vuyuvohure/edit?html,js,console
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