0

I'm creating a JavaScript object, and would like to be able to reactively detect changes in a passed in object.

I've tried to use Proxy objects, but have been unable to reproduce the desired behavior. An example I tried to implement into my code was this: Listening for variable changes in JavaScript

Here is the very basic shell of the constructor I am using:

function Fluid(options) {
    this.options = options;
    // Here is where I use the options object, and would like to be able to re-evaluate certain pieces of code if any values in 'this.options' changes.
}

let myApp = new Fluid({
    testValue: 1
});

My expected output could be something like this:

function Fluid(options) {
    this.options = options;

    function doThings() {
        if(this.options.testValue === 1) {
            console.log("The value is 1");
        } else {
            console.log("The value is not 1");
        }
    }

    doThings();

    // Here I would implement the code to detect changes in the this.options object, and if this.options changes, I can execute a function, like doThings()

}

let myApp = new Fluid({
   testValue: 1
});

// Console: The value is 1

myApp.testValue = 2;

// Console: The value is not 1
Infrared
  • 140
  • 9

1 Answers1

1

After expirimenting more the Proxy objects, I was able to fix this problem by using the following code:

function Fluid(options) {
    this.options = options;

    let proxyHandler = {
        set: (target, objectKey, value) => {
            console.log(`Setting property "${objectKey}" = "${value}"`);
            return target[objectKey] = value;
        }
    };

    this.options = new Proxy(this.options, proxyHandler);

}
Infrared
  • 140
  • 9