I have
getEventNameFromInput() {
this.inputName.addEventListener('keyup', this.eventName())
}
eventName() {
let eventName = [];
return (e) => {
eventName.push(e.target.value)
}
};
I try to use in second object but doesnt' work. :
interfaceUser.inputName.removeEventListener('keyup', interfaceUser.eventName())
This and interfaceuser are references the same instance of object. getEventNameFromInput and eventName are in object InterfaceUser
CodePudding user response:
When you call removeEventListener
you have to pass the same function.
With your existing code, every time you call eventName
, it generates a new arrow function and returns that. An identical function will not do the job. You need the same function.
This means that you need to store the function when you create it, and then retrieve the value from the store next time you need it.
For example:
eventName() {
if (!this.eventHandler) {
let eventName = [];
this.eventHandler = (e) => {
eventName.push(e.target.value)
}
}
return this.eventHandler;
};
CodePudding user response:
I would suggest to go with custom events as specified here: https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events
const form = document.querySelector('form');
const textarea = document.querySelector('textarea');
form.addEventListener('awesome', e => console.log(e.detail.text()));
textarea.addEventListener('input', function() {
// Create and dispatch/trigger an event on the fly
// Note: Optionally, we've also leveraged the "function expression" (instead of the "arrow function expression") so "this" will represent the element
this.dispatchEvent(new CustomEvent('awesome', {
bubbles: true,
detail: {
text: () => textarea.value
}
}))
});
<form>
<textarea></textarea>
</form>