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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.