Search⌘ K
AI Features

Proxy Pattern: Change Observer pattern with Proxy

Explore how to implement the Change Observer pattern using ES2015 Proxy in Node.js. Understand how to create observable objects that detect property changes, trigger updates, and apply this to real-world scenarios like automatic invoice total recalculation.

We'll cover the following...

Change Observer pattern

The Change Observer pattern is a design pattern in which an object (the subject) notifies one or more observers of any state changes so that they can “react” to changes as soon as they happen.

Note: Although very similar, the Change Observer pattern shouldn’t be confused with the Observer pattern. The Change Observer pattern focuses on allowing the detection of property changes, while the Observer pattern is a more generic pattern that adopts an event emitter to propagate information about events happening in the system.

Proxies turn out to be quite an effective tool to create observable objects. Let’s see a possible implementation with the create-observable.js file.

Node.js
export function createObservable (target, observer) {
const observable = new Proxy(target, {
set (obj, prop, value) {
if (value !== obj[prop]) {
const prev = obj[prop]
obj[prop] = value
observer({ prop, prev, curr: value })
}
return true
}
})
return observable
}

In the preceding code, createObservable() accepts a target object (the object to observe for changes) and an observer ...