Answer the question
In order to leave comments, you need to log in
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);
}
});
Answer the question
In order to leave comments, you need to log in
keep access to el and binding
dataset gives us the ability to save only primitives
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question