Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 29

Implementing Observable Objects with Proxy 'set' Trap

This lesson is built with resources from youtube.com, newfinds.com and 1 more site.

Hello! Welcome to the next lesson in our journey through JavaScript's metaprogramming features.

In our last lesson, we established a crucial best practice: always using the Reflect API for default forwarding within Proxy traps. We saw how this prevents subtle but critical bugs related to the this context, ensuring our proxies are robust and behave predictably.

Today, we're going to put that knowledge to work on a very practical and powerful pattern. Our goal is to build an observable object that notifies subscribers of property changes using a 'set' trap. This concept, often called "reactivity," is the magic behind modern frontend frameworks like Vue and React, where the UI automatically updates in response to data changes. As a full-stack engineer, understanding this mechanism provides deep insight into how these frameworks operate under the hood.

1. The Core Idea: What is Reactivity?

In standard JavaScript, if you have a variable that depends on another, it doesn't automatically update when the dependency changes.

let price = 10;
let quantity = 2;
let total = price * quantity;

console.log(total); // 20

price = 20;
console.log(total); // Still 20!

To make total "react" to the change in price, we need a system to track this dependency and re-run the calculation. This is the essence of reactivity. Before we build this with modern Proxies, it's useful to understand the foundational concepts.

JavaScript Reactivity Explained Visually

The video "JavaScript Reactivity Explained Visually" from the Vue Mastery channel provides an excellent step-by-step conceptual overview of how a reactivity system is built from scratch. It uses an older technique, Object.defineProperty, which we will soon replace with Proxies.

Please watch the following segments to understand the classic Observer pattern and how it was implemented before ES6 Proxies: 3:46 - 6:02: Focus on the Dep (Dependency) class. This is a classic implementation of the Observer pattern, with depend() to register subscribers and notify() to alert them. 8:27 - 10:28: Pay attention to how Object.defineProperty is used to create custom get and set functions on an object's properties. This is the interception mechanism. 12:18 - 14:15: See how the Dep class and Object.defineProperty are combined. The key is that dep.depend() is called in the getter and dep.notify() is called in the setter. This is the core reactive loop.

The video demonstrates the key components:

  1. Dependency Store (Dep class): An object responsible for keeping a list of subscribers (or "watchers").
  2. Interception (Object.defineProperty): A way to run code when a property is read from (get) or written to (set).
  3. Connection: When a property is accessed, the current "watcher" is subscribed. When the property is changed, all its subscribers are notified.

While Object.defineProperty works, it has limitations. It must be run for each property individually, it doesn't work for new properties added later, and it can't intercept delete. This is where Proxy offers a more elegant and powerful solution.


2. Building an Observable with a Proxy

We can achieve a much cleaner implementation using a Proxy. A single set trap can intercept writes to any property on the object, including properties that don't exist yet.

Let's build a function, createObservable, that takes a target object and a list of subscribers (callbacks) and makes it reactive.

Our first version will be simple: any change to any property will notify all subscribers.

function createObservable(target, subscribers) {
  const handler = {
    set(target, prop, value, receiver) {
      console.log(`Setting property "${prop}" to`, value);

      // Perform the actual update using Reflect (as we learned!)
      const success = Reflect.set(target, prop, value, receiver);

      if (success) {
        // Notify all subscribers about the change
        subscribers.forEach(callback => callback());
      }
      
      return success;
    }
  };

  return new Proxy(target, handler);
}

// --- Usage ---
const subscribers = [
  () => console.log("Notification 1: State has changed!"),
  () => console.log("Notification 2: Something was updated.")
];

const state = createObservable({ count: 0, user: 'Alex' }, subscribers);

state.count = 1; 
// LOG: Setting property "count" to 1
// LOG: Notification 1: State has changed!
// LOG: Notification 2: Something was updated.

state.user = 'Bob';
// LOG: Setting property "user" to Bob
// LOG: Notification 1: State has changed!
// LOG: Notification 2: Something was updated.

This already accomplishes the basic goal! The set trap successfully intercepts property assignments and triggers our subscriber functions.


3. A More Practical Implementation

The simple approach is a good start, but in a real application, subscribers usually need more information. What changed? What was the old value? Let's improve our createObservable function to provide these details.

We can also make the subscriber management more dynamic. Instead of passing subscribers at creation, we'll create a self-contained observable object with a method to subscribe.

This approach is detailed in the following article. We'll be creating a similar buildProxy function that takes a single callback, but we will adapt it to manage a list of subscribers.

Create an Observable Object using Proxy

The article "Create an Observable Object using Proxy" provides a fantastic, clean implementation of this pattern. It builds the solution from the ground up, culminating in a function that uses a callback to report detailed change information.

Please read the sections "Callback instead of logging" and "Wrapping up". Focus on how the set trap is modified to invoke a callback function with a detailed payload (action, path, newValue, previousValue). We will adapt this idea for our system.

Drawing inspiration from that article, let's create a more robust Observable factory.

function Observable(target) {
  // 1. A private list of subscribers
  const subscribers = new Set();

  const handler = {
    set(obj, prop, value, receiver) {
      // Get the old value before setting the new one
      const oldValue = Reflect.get(obj, prop, receiver);

      // We only notify if the value has actually changed
      if (oldValue === value) {
        return true;
      }
      
      const success = Reflect.set(...arguments);

      if (success) {
        // Create a detailed change object
        const change = { prop, oldValue, newValue: value };
        // Notify all subscribers with the details
        subscribers.forEach(callback => callback(change));
      }

      return success;
    }
    // We could also implement `deleteProperty` here to notify on deletions
  };

  const proxy = new Proxy(target, handler);

  // 2. Return the proxy and a subscribe method
  return {
    proxy,
    subscribe(callback) {
      subscribers.add(callback);
      // Return an 'unsubscribe' function for cleanup
      return () => subscribers.delete(callback);
    }
  };
}

// --- Usage ---
const { proxy: state, subscribe } = Observable({ count: 10, message: "Hello" });

const unsubscribeLogger = subscribe(change => {
  console.log(`LOGGER: Property '${change.prop}' changed from '${change.oldValue}' to '${change.newValue}'`);
});

const unsubscribeUpdater = subscribe(change => {
  if (change.prop === 'count') {
    console.log(`UPDATER: Count updated. New percentage is ${change.newValue * 10}%`);
  }
});

state.count = 11;
// LOG: LOGGER: Property 'count' changed from '10' to '11'
// LOG: UPDATER: Count updated. New percentage is 110%

state.message = "Hi";
// LOG: LOGGER: Property 'message' changed from 'Hello' to 'Hi'
// (UPDATER is not triggered for 'message' change because of its internal logic)

// Unsubscribe the logger
unsubscribeLogger();

state.count = 12;
// LOG: UPDATER: Count updated. New percentage is 120%
// (LOGGER is no longer called)

This is a much more flexible and powerful pattern. We have encapsulated the subscriber list, provided detailed change information, and given the consumer a way to unsubscribe, which is crucial for preventing memory leaks.

Test your understanding!

Extend the Observable factory to also handle property deletions. Implement the deleteProperty trap in the handler. When a property is deleted, it should notify all subscribers with a change object like: { prop: 'propertyName', action: 'delete', oldValue: 'the_value_that_was_deleted' }.

Show answer

Here's how you can add the deleteProperty trap to the handler:

function Observable(target) {
  const subscribers = new Set();

  const handler = {
    set(obj, prop, value, receiver) {
      // ... (same as before)
      const oldValue = Reflect.get(obj, prop, receiver);
      if (oldValue === value) return true;
      const success = Reflect.set(...arguments);
      if (success) {
        const change = { prop, oldValue, newValue: value, action: 'set' };
        subscribers.forEach(callback => callback(change));
      }
      return success;
    },

    deleteProperty(obj, prop) {
      // Get the old value before deleting
      const oldValue = Reflect.get(obj, prop);
      const success = Reflect.deleteProperty(obj, prop);

      if (success) {
        const change = { prop, oldValue, action: 'delete' };
        subscribers.forEach(callback => callback(change));
      }
      
      return success;
    }
  };

  const proxy = new Proxy(target, handler);

  return {
    proxy,
    subscribe(callback) {
      subscribers.add(callback);
      return () => subscribers.delete(callback);
    }
  };
}

// --- Usage ---
const { proxy: user, subscribe } = Observable({ name: "Alice", age: 30 });

const unsubscribe = subscribe(change => console.log(change));

delete user.age;
// LOG: { prop: 'age', oldValue: 30, action: 'delete' }

4. Advanced: Property-Level Subscriptions

Our current implementation is great, but it has one inefficiency: every subscriber is notified of every change. The subscriber then has to check if it's interested in that particular property.

For a truly optimized system, like those in UI frameworks, we want a subscriber to be notified only when a property it actually uses is changed. This requires connecting the get and set traps.

The logic is as follows:

  1. We maintain a map of dependencies: property -> Set<subscribers>.
  2. We also have a global variable, currentSubscriber, that points to the subscriber function that is currently running.
  3. During get: When a property is accessed, we check if currentSubscriber is set. If it is, we know that this subscriber depends on this property. We add it to the dependency map for that property.
  4. During set: When a property is modified, we look up that property in our dependency map and notify only the subscribers in the corresponding Set.

This creates a highly efficient system that automatically tracks which parts of your code depend on which pieces of data.

Writing a JavaScript Framework - Data Binding with ES6 Proxies

The article "Writing a JavaScript Framework - Data Binding with ES6 Proxies" implements exactly this advanced dependency-tracking logic. It provides a complete picture of how a production-grade reactivity system works.

Read the sections "Implementing a simple observable" and the step-by-step description that follows. Focus on the interplay between currentObserver, the get trap (which calls registerObserver), and the set trap (which queues the relevant observers).

This advanced pattern is the secret sauce behind the performance of many modern libraries and a testament to the power of combining the get and set proxy traps.


Conclusion

In this lesson, you've built a powerful and practical tool using your knowledge of Proxy and Reflect. We've seen how to intercept property modifications and notify interested parties, which is a cornerstone of modern reactive programming in JavaScript.

Key Takeaways:

  • An observable object is one that notifies subscribers when its state changes.
  • The Proxy set trap is the ideal mechanism for intercepting these changes, as it's efficient and handles all properties, including newly added ones.
  • A robust observable implementation should manage a list of subscribers, provide detailed information about what changed (prop, oldValue, newValue), and offer a way to unsubscribe.
  • For advanced use cases, you can combine the get and set traps to create a dependency tracking system, where subscribers are only notified about changes to properties they have explicitly accessed.

Next Up

We've focused heavily on the set trap today. In our next lesson, we'll shift our attention to creative uses of the get trap. You will learn how to implement negative array indexing or default property values using a get trap, further expanding your metaprogramming toolkit.