监听 JavaScript 中的变量变化 [英] Listening for variable changes in JavaScript

查看:49
本文介绍了监听 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 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 对象的唯一缺点是:

  1. Proxy 对象在旧版浏览器(例如 IE11)和 polyfill 不能完全复制 Proxy 功能.
  2. 代理对象在处理特殊对象(例如,Date)时并不总是按预期运行——Proxy 对象最好与普通对象或数组配对.
  1. The Proxy object is not available in older browsers (such as IE11) and the polyfill cannot fully replicate Proxy functionality.
  2. Proxy objects do not always behave as expected with special objects (e.g., Date) -- the Proxy 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆