Seeking a solution using JavaScript (ES6), I am in need of referencing a handler function called onKeyup
. This will allow me to both add and remove an event listener in two functions that are declared within the same object.
Can you suggest how I can access the onKeyup
function from the bind
and unbind
functions within the object? :
export default {
bind(el) {
let privateVar = 42;
function foobar() {
console.log('Foobar hit', privateVar);
}
function onKeyup() {
console.log('onKeyup hit');
foobar();
}
el.addEventListener("keyup", onKeyup, false);
},
unbind(el) {
//`onKeyup` does not exist here, how can I fix that?
el.removeEventListener("keyup", onKeyup, false);
}
}
Is there a feasible way to achieve this?
One initial approach would involve modifying the code as follows, however, it may lead to decreased readability :
export default {
privateVar : null,
onKeyup() {
console.log('onKeyup hit');
this.foobar();
},
foobar() {
console.log('Foobar hit', this.privateVar);
},
bind(el) {
this.privateVar = 42;
el.addEventListener("keyup", this.onKeyup, false);
},
unbind(el) {
el.removeEventListener("keyup", this.onKeyup, false);
}
}
Do you have suggestions for a better, cleaner approach?
Note: The structure of the bind
and unbind
functions within the object cannot be altered, as it is utilized as a directive declaration for Vue.js 2.*.
EDIT:
I also attempted an alternative organization of my code:
export default {
onKeyup : null,
bind(el) {
let privateVar = 42;
function foobar() {
console.log('Foobar hit', privateVar);
}
this.onKeyup = function() {
console.log('onKeyup hit');
foobar();
};
el.addEventListener("keyup", this.onKeyup, false);
},
unbind(el) {
el.removeEventListener("keyup", this.onKeyup, false);
}
}
...however, this resulted in the error message:
Uncaught TypeError: Cannot set property 'onKeyup' of undefined