0

I have a function like so:

mouseClickNav() {

    document.getElementById('mouseClickNav').style.width = '319px';
    let ctx: CanvasRenderingContext2D = this.canvasTest.nativeElement.getContext('2d');

    ctx.canvas.addEventListener('click', (event) => {
        var mouseX = event.clientX - ctx.canvas.offsetLeft;
        var mouseY = event.clientY - ctx.canvas.offsetTop;
        this.mouseClickX = mouseX;
        this.mouseClickY = mouseY;
    });

Which works fine, and adds the event listener. However, I cannot seem to figure out how to remove it after im done with it. The next function is where i want to remove the listener:

closeMouseClickNav() {
    document.getElementById('mouseClickNav').style.width = '0';
    let ctx: CanvasRenderingContext2D = this.canvasTest.nativeElement.getContext('2d');
    ctx.canvas.removeEventListener('click', () => { });
 }

Not sure what I am doing wrong here. I declared the listener and added it, when i remove it doesnt it have to be the same?

  • Possible duplicate of [Javascript removeEventListener not working](https://stackoverflow.com/questions/10444077/javascript-removeeventlistener-not-working) – JJJ Sep 23 '18 at 13:47
  • except im not using vanilla js, im using typescript. perhaps im just not understanding how to use an event listener. should i make the above a function, and then add that function to the event listener? – josh_winters Sep 23 '18 at 13:53
  • Typescript doesn't make any difference. You're adding one function as an event listener and then try to remove a completely different function which will obviously not work. – JJJ Sep 23 '18 at 13:55
  • So how can i access the same function in different functions? IE function 1 has a function called handler inside it, then calls an add event listener. function 2 then needs to somehow get that function, and remove the event listener? – josh_winters Sep 23 '18 at 14:05
  • Yes. The duplicate shows how to do it. – JJJ Sep 23 '18 at 14:29

0 Answers0