D
D
Daniil Popov2018-11-07 12:51:25
Vue.js
Daniil Popov, 2018-11-07 12:51:25

How to correctly add and remove event handlers in a directive (Vue)?

I understand directives and at the same time I try to create my own. But I ran into a problem: if you use an external function, then when binding (bind) it is possible to add an event handler to the element, and when unbinding (unbind), respectively, remove it, but how can you save access to el and binding?
Example:

function getKey(e) {
  console.log("key", e.key);
  console.log("binding.value", binding.value); // недоступно через замыкания
}

Vue.directive("input-test", {
  bind: function(el, binding) {
    el.addEventListener("keydown", getKey); 
  },
  unbind: function(el) {
    el.removeEventListener("keydown", getKey);
  }
});

How to solve this problem and are there any good practices for such situations? Is it possible to create internal functions for a directive that will be available in all hooks?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-11-07
@groog

keep access to el and binding

The element will be available as this.
As for binding, you can use a dataset to pass a value. For example .
UPD. Taken from the comments:
dataset gives us the ability to save only primitives

You can attach the object of interest to an element as its property, like this . Or use Map/WeakMap where the element is the key, like .
In general, it is possible that you have chosen the wrong tool to solve your problem, and here you should use a component instead of a directive.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question