简体   繁体   English

JavaScript构造函数侦听此变量更改

[英]JavaScript constructor listen for this variable change

I'm creating a JavaScript object, and would like to be able to reactively detect changes in a passed in object. 我正在创建一个JavaScript对象,并且希望能够以反应方式检测传入的对象中的更改。

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 我尝试在代码中实现的一个示例是: 侦听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

After expirimenting more the Proxy objects, I was able to fix this problem by using the following code: 在试用了更多Proxy对象之后,我可以使用以下代码解决此问题:

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);

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM