patchEvents keeps a DOM element’s event listeners aligned with the old and new virtual-node handlers. It removes obsolete listeners, replaces changed ones, adds new ones, and returns the listeners now attached. section 8.2.5
Its implementation follows a small sequence:
- Compare oldEvents and newEvents with objectsDiff() to identify removed, added, and updated event names. section 8.2.5
- Remove listeners for removed or updated events by using the corresponding functions stored in oldListeners. section 8.2.5
- Attach listeners for added or updated handlers and collect the attached listener functions in a new object. section 8.2.5
- Save the returned object as newVdom.listeners so a later patch can remove these listeners. section 8.2.5
Patching a changed click handler
When a virtual node changes its click handler, patchEvents removes the old stored listener, attaches the new handler, and returns the replacement listener for future updates. section 8.2.5
Listing 8.11 Patching an element node (patch-dom.js)
function patchElement(oldVdom, newVdom) {
const el = oldVdom.el
const {
class: oldClass,
style: oldStyle,
on: oldEvents,
...oldAttrs
} = oldVdom.props
const {
class: newClass,
style: newStyle,
on: newEvents,
...newAttrs
} = newVdom.props
const { listeners: oldListeners } = oldVdom
patchAttrs(el, oldAttrs, newAttrs)
patchClasses(el, oldClass, newClass)
patchStyles(el, oldStyle, newStyle)
newVdom.listeners = patchEvents(el, oldListeners, oldEvents, newEvents)
}
// TODO: implement patchAttrs()
// TODO: implement patchClasses()
// TODO: implement patchStyles()
// TODO: implement patchEvents()
The element-patching listing shows where patchEvents receives old listeners and event maps, then stores its result on the new virtual node. section 8.2.5
