监听 JavaScript 中的变量变化 [英] Listening for variable changes in JavaScript
问题描述
JS 中是否有可能在某个变量的值发生变化时触发一个事件?接受 JQuery.
Is it possible to have an event in JS that fires when the value of a certain variable changes? JQuery is accepted.
推荐答案
这个问题最初发布于 2009 年,现有的大多数答案要么过时、无效,要么需要包含大型臃肿的库:
This question was originally posted in 2009 and most of the existing answers are either outdated, ineffective, or require the inclusion of large bloated libraries:
- Object.watch 和Object.observe 已被弃用和不应使用.
- onPropertyChange 是一个 DOM 元素事件处理程序仅适用于某些版本的 IE.
- Object.defineProperty 允许您可以使对象属性不可变,这将允许您检测尝试的更改,但它也会阻止任何更改.
- 定义 setter 和 getter 有效,但它需要大量设置代码,并且在您需要删除或创建新属性时效果不佳.
- Object.watch and Object.observe are both deprecated and should not be used.
- onPropertyChange is a DOM element event handler that only works in some versions of IE.
- Object.defineProperty allows you to make an object property immutable, which would allow you to detect attempted changes, but it would also block any changes.
- Defining setters and getters works, but it requires a lot of setup code and it does not work well when you need to delete or create new properties.
自 2018 年起,您现在可以使用 代理 对象 监视(并拦截)对对象所做的更改.它是专为 OP 尝试做的事情而构建的.这是一个基本示例:
As of 2018, you can now use the Proxy object to monitor (and intercept) changes made to an object. It is purpose built for what the OP is trying to do. Here's a basic example:
var targetObj = {};
var targetProxy = new Proxy(targetObj, {
set: function (target, key, value) {
console.log(`${key} set to ${value}`);
target[key] = value;
return true;
}
});
targetProxy.hello_world = "test"; // console: 'hello_world set to test'
Proxy
对象的唯一缺点是:
Proxy
对象在旧版浏览器(例如 IE11)和 polyfill 不能完全复制Proxy
功能.- 代理对象在处理特殊对象(例如,
Date
)时并不总是按预期运行——Proxy
对象最好与普通对象或数组配对.
- The
Proxy
object is not available in older browsers (such as IE11) and the polyfill cannot fully replicateProxy
functionality. - Proxy objects do not always behave as expected with special objects (e.g.,
Date
) -- theProxy
object is best paired with plain Objects or Arrays.
如果您需要观察对嵌套对象所做的更改,则需要使用专门的库,例如Observable Slim (我已发布).它是这样工作的:
If you need to observe changes made to a nested object, then you need to use a specialized library such as Observable Slim (which I have published). It works like this:
var test = {testing:{}};
var p = ObservableSlim.create(test, true, function(changes) {
console.log(JSON.stringify(changes));
});
p.testing.blah = 42; // console: [{"type":"add","target":{"blah":42},"property":"blah","newValue":42,"currentPath":"testing.blah",jsonPointer:"/testing/blah","proxy":{"blah":42}}]
这篇关于监听 JavaScript 中的变量变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!