在Javascript数组上生成事件

Generating event on Javascript array

本文关键字:事件 Javascript 数组      更新时间:2023-09-26

当Javascript数组的内容被修改时,如何生成一个事件,即当push或pop操作在特定Javascript数组上执行时,应该生成一个事件。基本上,我想跟踪在特定Javascript数组上执行的push、pop操作。

编辑:-在注释中说明的解决方案需要重写push或pop方法。我想在不重写的情况下执行它。

这个想法是数组是对象,所以你可以定义属性。

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定义一个push属性。房地产法。

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);
   }
});

我认为没有原生的方法可以做到这一点。这里也讨论了这个主题,建议的解决方案是为数组实现一个包装器类。

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