Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove an event created with vnode.context.$on in a Vue directive?

Tags:

vue.js

On directive bind I created a listener to the event 'validate' to run the function updateMessage:

vnode.context.$on('validate', () => {
   updateMessage(el, vm);
});

How Can i remove or override it when i unbind the directive?

directives: {
    validate: {
      bind(el, _, vnode) {
        const vm = vnode.context;
        el.addEventListener('input', e => {
                updateMessage(e.target, vm);
        });
        vnode.context.$on('validate', () => {
                updateMessage(el, vm);
        });
          console.log('bind', el)
      },
     unbind(el, _, vnode) {
        el.removeEventListener('input', e => {
                updateMessage(e.target, vm);
        });
         console.log('unbind',el)
     },
    }
  },
like image 433
fparaggio Avatar asked Oct 23 '25 02:10

fparaggio


1 Answers

To remove this specific event handler, you'll need to store a reference to the handler function. You'll need to do the same for your input event handler too.

For example (assuming updateMessage is defined somewhere), store the event handlers on the element instances so you can reference them later

validate: {
  bind(el, _, vnode) {
    const vm = vnode.context
    el.inputEventHandler = e => updateMessage(e.target, vm)
    el.validateEventHandler = () => updateMessage(el, vm)
    
    el.addEventListener('input', el.inputEventHandler)
    vm.$on('validate', el.validateEventHandler)
  },
  unbind(el, _, vnode) {
    el.removeEventListener('input', el.inputEventHandler)
    vnode.context.$off('validate', el.validateEventHandler)
  }
}

Thanks to Decade Moon for the idea about storing the functions on the element.

like image 179
Phil Avatar answered Oct 25 '25 21:10

Phil