9
Researching I found Event
and CustumEvent
, both can be used to create events, and to control registrations, removals and emissions of the event should be used EventTarget
, but I didn’t understand how they work, for example, how I could create a custom click event?
//Cria um evento de clique personalizado
const myClick = new Event('myClick');
//Alguma coisa para guardar as chamadas de "addEventListener"
//Adiciona um ouvinte do evento personalizado aos elmentos
myElement.addEventListener('myClick', event => console.log(event));
myOtherElement.addEventListener('myClick', event => console.log(event));
//Quando houver um clique na tela
window.addEventListener('click', function(event) {
//Percorre uma lista onde ficaria armazenado os elementos que foram adicionado ouvintes do evento
for(element of elementList) {
//Se o elemento for igual ao elemento principal do clique na janela
if (event.target === element) {
//Dispara o evento customizado de clique
element.dispatchEvent(myClick);
}
}
});
Am I on the right track? How to save calls from addEventListener
?
The example is exactly like the click event that already exists, it’s just an example. At the moment I just want to know how it is done in modern browsers, I’m not worried about compatibility
But that way it would have to add two events every time, it wouldn’t be automatic. For example, assuming I want to add an event in three elements, I would also have to add three normal click event listeners in those same 3 elements, if so it would be better to add just one and encapsulate what would make my special event a function that would call in the first line of the listener’s callback
– Costamilam
That’s what you need to do. I believe there’s no other way.
– Luiz Felipe