removeEventListener does not work

This is my addEventListener wich is working fine in mounted

document.addEventListener('keyup', function(event) {
        if (event.keyCode == 13) {
          vm.confirmArrival();
        }
      }, true);

but i cant get removeEventListener working in destroyd.
Ty for any help

Hi!

So you need ENTER key to always call confirmArrival() method or you need it only on specific form/element?

Also what error you get that you think it’s not working?

1 Like

Please use the proper formatting for you code blocks.

1 Like

I created my component as modal. and there for confirmation enter work fine, but when I wont to remove event listener in destroyed I can’t. And when modal is closed event handler is still on. Do you have any suggestion?

Use the built in event handling system with a key modifier.

1 Like

What makes you think that your modal component is actually destroyed? Such listeners should be destroyed on beforeDestroy life cycle hook.

If you are showing/hiding your modal using a simple boolean flag then add an extra check in your event listener for future calls to open/close your modal.

1 Like

Tried beforeDestroy, did’t work.

How to bind button with key modifier?

This sort of reply is frustrating for users to respond to and help with. What exactly didn’t work. Did you get an error message. If not, is your event listener still listening? Does beforeDestroy just never get called.

1 Like

I’m guilty, I was passing this.foo(event) to addEventlisener.
This is how it should be:

destroyed(){
    document.removeEventListener('keyup', this.foo);
  },
  mounted(){
    document.addEventListener('keyup',  this.foo);
  },
methods:{
foo(event){
        if (event.keyCode == 13) {
          this.confirmArrival();
        }
    }
]
3 Likes

Thanks man you saved mine time great job.!!!

I noticed in an app I’m working on that keyup events were triggering multiple times (and increasing) after switching views. I implemented a ‘removeEventListener’ in ‘destroyed’, and then ‘beforeDestroy’ but the multiple events persisted. Your code reminded me that I had to pass the specific method, i.e.,

window.removeEventListener('keyup', this.detectKeys);

rather than:

window.removeEventListener('keyup', null);

(granted this is a vanilla javascript factoid but fwiw …)

cheers!

Whiskey T.