...

/

Proxy Pattern: Change Observer pattern with Proxy

Proxy Pattern: Change Observer pattern with Proxy

Learn how to use reactive programming using the ES2015 Proxy.

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.

Press + to interact
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 ...