简体   繁体   English

如何通过回调观察 window.variable 的变化?

[英]How do I watch a window.variable change with a callback?

I have a global variable and its type is String :我有一个全局变量,它的类型是String

window.my_global_var = 'string';

It might be changed by some external-loaded JavaScript files or an AJAX request.它可能会被一些外部加载的 JavaScript 文件或 AJAX 请求更改。 So I want to watch it and invoke a callback when it's updated.所以我想观看它并在更新时调用回调。

I searched a while but found Object.observe is already deprecated.我搜索了一会儿,但发现 Object.observe 已被弃用。 I found an answer but it is better used to observe an object, not a String window.variable.我找到了一个答案,但最好用来观察 object,而不是 String window.variable。

The worst approach would be using a setInterval to watch it but I guess it's too stupid.最糟糕的方法是使用setInterval来观看它,但我想这太愚蠢了。

Is there any good way to do this?有什么好办法吗?

You can use Object.defineProperties on window :您可以在Object.defineProperties上使用window

function onValueUpdate(my_global_var) {
   // Some arbitrary logic you want to execute on callback
   console.log(`my_global_var was updated: ${my_global_var}`);
}

Object.defineProperties(window, {
    _my_global_var: {
        value: 'string',
        writable: true
    },
    my_global_var: {
        get: function() {
            return this._my_global_var;
        },
        set: function(val) {
            this._my_global_var = val;
            onValueUpdate(this._my_global_var);
        }
    }
});

window.my_global_var = 'New string';

When you access window.my_global_var it behaves exactly as the property of type String would.当您访问window.my_global_var时,它的行为与String类型的属性完全一样。 But when you set it you can adjust it to use any additional logic.但是当你设置它时,你可以调整它以使用任何额外的逻辑。

Function onValueUpdate needs to be public (or you can use a public method instead). Function onValueUpdate需要公开(或者您可以改用公开方法)。

There's a warning against this approach in the answer you've found though:不过,在您找到的答案中有针对这种方法的警告

I'd not go with getters/setters solution - it's complicated, not scalable and not maintainable.我不会 go 使用 getters/setters 解决方案 - 它很复杂,不可扩展且不可维护。

So if you need scalability you probably should look for some library that can do that.因此,如果您需要可伸缩性,您可能应该寻找一些可以做到这一点的库。 Otherwise this should work just as well.否则这也应该有效。

You could wrap the global object in a proxy with a set handler .您可以使用set handler将全局 object 包装在代理中。 You would need to pass the proxy around your program, rather than relying implicitly on the global object, however.但是,您需要围绕您的程序传递代理,而不是隐式依赖全局 object。

 const handler = { set(obj, prop, value) { if (prop === 'foo') console.log(`Property updated with value: ${value}.`) return Reflect.set(..;arguments) } }, const proxy = new Proxy(window; handler). proxy:foo = 1 // "Property updated with value. 1." proxy.bar = 2 console.log(foo) // 1 console.log(bar) // 2

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

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