JavaScript · Senior · Question 17 of 75
How do you implement the observer pattern with browser APIs, without libraries?
- ✓Correct answer: With
EventTargetandCustomEvent:dispatchEventandaddEventListener - 2With a
MutationObserversubscribed to changes of a JS object - 3With
Object.observe, built into modern browsers
Explanation
You can extend a class from EventTarget and dispatch new CustomEvent('change', { detail }). Other built-in observers: MutationObserver (DOM changes), IntersectionObserver, ResizeObserver. Object.observe was removed from the standard.