34
loading...
This website collects cookies to deliver better user experience
element
and we want to add event listeners to it. How would you do so ?const handleClick = () =>{console.log('You can remove me later safely')}
element.addEventListener('click',handleClick);
element.addEventListener('click',()=>console.log('Try and remove me noob'));
element.removeEventListener('click',handleClick);
const someObj = {
handleEvent: (e)=>console.log(`I am ${e.type} event`);
}
element.addEventListener('click',someObj);
element.removeEventListener('click',someObj);
Handler
class which can abstract the registration and unregistration bit and work on the same principle ? class Handler {
#element
#eventMap = {}
constructor(element, eventMap) {
this.#element = element
this.register(eventMap)
}
handleEvent(e) {
this.#eventMap[e.type](e)
}
register(eventMap) {
this.#eventMap = { ...this.#eventMap, ...eventMap }
Object.keys(this.#eventMap).forEach((event) => {
this.#element.addEventListener(event, this)
})
}
unregister(event) {
this.#element.removeEventListener(event, this)
}
unregisterAll() {
Object.keys(this.#eventMap).forEach((event) => {
this.#element.removeEventListener(event, this)
})
}
}
add/removeEventListener
, we can have a custom Handler
class inside which this
will point to the object instance and come into use. const handler = new Handler(element, {
click: ()=>console.log('Yo I am clicky'),
focus: ()=>console.log('FOCUS!!!'),
});
element
, it registers both the anonymous functions for respective events. And if you go further to register another function for click
like so :-handler.register({
click: () => console.log('Well I am new clicky')
});
click
function that we had without any worry of handling its removal and add this new anonymous function. unregister
the click
function, how would you do so ?handler.unregister('click');
Handler
class will ensure that for each event type, only one function is registered for the same element. But what if I want to register multiple functions for same event type for the same element ?Handler
class with same element
and let it be responsible for it. handleEvent
.