JS ⟩ browser ⟩ event ⟩ handler ⟩ register ⟩ object handler
delegate event handling to an object:
elem.addEventListener('click', { // calls handleEvent(event) in case of an event. handleEvent(event) { ... } // ⭐️ required method });
could also use a class instance for that:
class Menu { // ⭐️ required method handleEvent(event) { switch(event.type) { case 'mousedown': ...; break; case 'mouseup' : ...; break; } } // other methods/properties ... } // Menu can also be written like this: class Menu { // ⭐️ required method handleEvent(event) { const methodName = "on" + event.type; // onmousedown, onmouseup ... this[methodName] ?. (event); // optional invocation } // methods for individual event onmousedown(event){ ... } onmouseup (event){ ... } } let menu = new Menu(); // object handler elem.addEventListener('mousedown', menu); elem.addEventListener('mouseup' , menu);
optional invocation ?.()
JS.info ⟩ object handlers
Last updated 1 year ago