Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Window remove eventListener resize function

Tags:

javascript

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?

like image 359
caramba Avatar asked Dec 24 '22 21:12

caramba


2 Answers

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);
like image 78
cyr_x Avatar answered Jan 04 '23 22:01

cyr_x


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

like image 44
Tiep Phan Avatar answered Jan 05 '23 00:01

Tiep Phan