1

如何在修改 Javascript 数组的内容时生成事件,即在对该特定 Javascript 数组执行推送或弹出操作时应生成事件。基本上,我想跟踪对特定 Javascript 数组执行的推送、弹出操作。

编辑:-评论中说明的解决方案需要覆盖 push 或 pop 方法。我想在不覆盖它的情况下执行它。

4

2 回答 2

0

我认为没有本地方法可以做到这一点。此处还讨论了此主题,建议的解决方案是为您的数组实现包装类。

另一种方法是仅实现包装push函数并在函数调用时触发事件。

于 2015-07-31T08:08:31.887 回答
0

这个想法是数组是对象,因此您可以定义属性。

var someArray = []; // a normal array

someArray.push = function() { // this will override the original push method
  // custom code here
  console.log('pushing something..');
  return Array.prototype.push.apply(this, arguments); // original push
};
// now everytime you push something a message will be logged. Change this functionality as you like.

注意: someArray.push() 现在将是可枚举的。如果你想防止这种情况,你可以使用 Object.property 方法定义一个“推送”属性。

Object.defineProperty(someArray, 'push', {
  enumerable: false, // it's false by default anyway
  value: function() {
    console.log('pushing something..');
    return Array.prototype.push.apply(this, arguments);
   }
});
于 2015-07-31T08:44:02.760 回答