Home >Web Front-end >JS Tutorial >How Can I Detect JavaScript Variable Changes?

How Can I Detect JavaScript Variable Changes?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-18 07:12:10416browse

How Can I Detect JavaScript Variable Changes?

Observing Variable Changes in JavaScript

Original Question:

Is there an event in JavaScript that triggers when the value of a specific variable is modified? Please consider solutions involving jQuery.

Answer:

Using Proxy Objects:

As of 2018, the Proxy object provides an effective mechanism for monitoring and intercepting object property changes. It works by creating a proxy object that wraps the target object.

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'

Limitations:

  • Proxy objects are not supported in older browsers (e.g., IE11).
  • They may exhibit unexpected behavior with special objects (e.g., Date).

Observing Nested Objects:

For observing changes in nested objects, Specialized libraries like Observable Slim offer a more comprehensive solution.

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}}]

The above is the detailed content of How Can I Detect JavaScript Variable Changes?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn