如何在修改 Javascript 数组的内容时生成事件,即在对该特定 Javascript 数组执行推送或弹出操作时应生成事件。基本上,我想跟踪对特定 Javascript 数组执行的推送、弹出操作。
编辑:-评论中说明的解决方案需要覆盖 push 或 pop 方法。我想在不覆盖它的情况下执行它。
如何在修改 Javascript 数组的内容时生成事件,即在对该特定 Javascript 数组执行推送或弹出操作时应生成事件。基本上,我想跟踪对特定 Javascript 数组执行的推送、弹出操作。
编辑:-评论中说明的解决方案需要覆盖 push 或 pop 方法。我想在不覆盖它的情况下执行它。
我认为没有本地方法可以做到这一点。此处还讨论了此主题,建议的解决方案是为您的数组实现包装类。
另一种方法是仅实现包装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);
}
});