addEventListeners registers the event handlers stored in a virtual node’s on object. It accepts an optional listener map and DOM element, adds each handler, and returns the registered listeners. section 4.1.5 section 4.1.4
Its implementation separates three small responsibilities:
- Iterate over event names and handler functions with Object.entries(). section 4.1.5
- Delegate each individual registration to addEventListener(eventName, handler, el). section 4.1.5
- Store the returned handlers in a new object for the virtual node’s listeners property. section 4.1.5 section 10.3
Registering a button’s handlers
A virtual button can describe several handlers together: on: { mouseover: () => console.log('almost yay!'), click: () => console.log('yay!'), dblclick: () => console.log('double yay!') }. Passing this object and the button element to addEventListeners attaches all three handlers. section 4.1.5
export function addEventListeners(listeners = {}, el) {
const addedListeners = {}
Object.entries(listeners).forEach(([eventName, handler]) => {
const listener = addEventListener(eventName, handler, el)
addedListeners[eventName] = listener
})
return addedListeners
}
The complete helper shows the default empty listener map, per-entry delegation, and separate returned mapping. section 4.1.5
