在Javascript数组上生成事件

在Javascript数组上生成事件,javascript,arrays,dom-events,custom-events,Javascript,Arrays,Dom Events,Custom Events,当Javascript数组的内容被修改时,我如何生成一个事件,即在特定Javascript数组上执行推送或弹出操作时,应该生成一个事件。基本上,我希望跟踪在特定Javascript数组上执行的推送、弹出操作 编辑:-注释中说明的解决方案需要覆盖推送或弹出方法。我想执行它而不重写它 我认为没有一种本土的方式可以做到这一点。还讨论了这个主题,建议的解决方案是为数组实现一个包装器类 另一种方法是只实现一个wrapperpush函数,并在函数调用时触发事件。我认为没有原生方法可以做到这一点。还讨论了这个

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


编辑:-注释中说明的解决方案需要覆盖推送或弹出方法。我想执行它而不重写它

我认为没有一种本土的方式可以做到这一点。还讨论了这个主题,建议的解决方案是为数组实现一个包装器类


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

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


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

其思想是数组是对象,因此您可以定义属性

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

其思想是数组是对象,因此可以定义属性

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

这回答了你的问题吗?这回答了你的问题吗?我将尝试第二种方法。看起来很有趣。我将尝试第二种方法。看起来很有趣。