javascript - 使用 Proxy 对象检测 Javascript 数组中的更改

标签 javascript

在 Javascript 中观察数组的变化是相对简单的。

我使用的一种方法是这样的:

// subscribe to add, update, delete, and splice changes
Array.observe(viewHelpFiles, function(changes) {
  // handle changes... in this case, we'll just log them 
  changes.forEach(function(change) {
    console.log(Object.keys(change).reduce(function(p, c) {
      if (c !== "object" && c in change) {
        p.push(c + ": " + JSON.stringify(change[c]));
      }
      return p;
    }, []).join(", "));
  });
});

但是,我最近读到 Array.observe已弃用,我们应该使用 proxy object instead.

我们如何检测 Proxy 对象数组的变化?我找不到任何例子,有人有兴趣详细说明吗?

最佳答案

从我可以从 MDN page 中读到的内容,您可以创建一个通用处理程序,您可以在其中处理对任何对象的所有更改。

从某种意义上说,您编写了一个拦截器,每次您从数组中获取值或设置值时都会进行干预。然后,您可以编写自己的逻辑来跟踪更改。

var arrayChangeHandler = {
  get: function(target, property) {
    console.log('getting ' + property + ' for ' + target);
    // property is index in this case
    return target[property];
  },
  set: function(target, property, value, receiver) {
    console.log('setting ' + property + ' for ' + target + ' with value ' + value);
    target[property] = value;
    // you have to return true to accept the changes
    return true;
  }
};

var originalArray = [];
var proxyToArray = new Proxy( originalArray, arrayChangeHandler );

proxyToArray.push('Test');
console.log(proxyToArray[0]);

// pushing to the original array won't go through the proxy methods
originalArray.push('test2');

// the will however contain the same data, 
// as the items get added to the referenced array
console.log('Both proxy and original array have the same content? ' 
  + (proxyToArray.join(',') === originalArray.join(',')));

// expect false here, as strict equality is incorrect
console.log('They strict equal to eachother? ' + (proxyToArray === originalArray));


然后输出:
getting push for 
getting length for 
setting 0 for  with value Test 
setting length for Test with value 1
getting 0 for Test
Test

代理的警告是,在对象上定义的所有内容都将被拦截,这可以在使用 push 时观察到。方法。

将被代理的原始对象不会发生变化,并且对原始对象所做的更改不会被代理捕获。

关于javascript - 使用 Proxy 对象检测 Javascript 数组中的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35610242/

相关文章:

javascript - 我收到了关于解构的作业,有人可以帮助我了解如何解构嵌套在数组 [ ] 中的对象 { } 吗?

javascript - 如何更改 CKEditor,使其不会自动将 <p></p> 放入文本区域?

javascript - 将 hoist-non-react-statics 与 withRouter 一起使用

javascript - 如何从 JSON 对象中选择 href

javascript - RequireJS 优化器是否可以在没有 "app.js"的情况下以及依赖于内联模块的模块上工作?

javascript - NgCordova:Uncaught ReferenceError: $cordovaOauth 未定义

javascript - 动态创建列表的 this 选择器也引用父级

javascript - disallowTrailingComma 在 jscs 中不起作用

javascript - 呈现标记 "on top of everything"(包括在 floatPane 中呈现的任何内容)

Javascript 文本文件加载延迟