0

I have a module function which sets up an addEventListener function and currently uses a global variable in the addEventListener function. I want to encapsulate this in an Object. But I can't see how to access the property from within the addEventListener function because 'this' within the addEventListener doesn't refer to my object ?

i.e

 let x=0;
 function mine (){
    window.addEventListener('click',listener);
    function listener(){
         dosomething with x;
    }
 } 
 function setX(y) {x=y};
 export {setX};

to

function Mine() {
  this.x=0;
  window.addEventListener('click',listener);
  function listener(){
    dosomething with this.x;
  }
}
Mine.prototype.setX = function(y) {this.x=y);
export {Mine};

the latter does not work because in a listener 'this' does not refer to 'Mine' (I think).

Any help appreciated.

mkc
  • 1
  • 1
  • Define `listener` as an *arrow* function and it will work: `var listener = () => { ....... }` – trincot Jan 16 '22 at 11:57
  • Great many thanks. I wanted to use the listener.bind(this) solution but had a problem because the listener function removed itself using removeEventListener which no longer worked. I was not sure whether this was a syntax problem (I tried removeEventListener(mouseUp) and removeEventListener(mouseUp.bind(this) but neither worked) or whether it is a limitation on bind (can't be used twice or somesuch). – mkc Jan 16 '22 at 23:32

0 Answers0