在Javascript中,当一个数组被推、弹出、移位或基于索引的赋值被修改时,有没有一种方法可以得到通知?我想要一个能触发我能处理的事件的东西。
我知道SpiderMonkey中的watch()
功能,但只有在将整个变量设置为其他值时,该功能才有效。
发布于 2015-07-22 19:45:49
通过阅读这里的所有答案,我组装了一个不需要任何外部库的简化解决方案。
它还更好地说明了该方法的一般思想:
function processQ() {
// ... this will be called on each .push
}
var myEventsQ = [];
myEventsQ.push = function() { Array.prototype.push.apply(this, arguments); processQ();};
发布于 2018-05-23 06:49:30
我使用了以下代码来侦听数组的更改。
/* @arr array you want to listen to
@callback function that will be called on any change inside array
*/
function listenChangesinArray(arr,callback){
// Add more methods here if you want to listen to them
['pop','push','reverse','shift','unshift','splice','sort'].forEach((m)=>{
arr[m] = function(){
var res = Array.prototype[m].apply(arr, arguments); // call normal behaviour
callback.apply(arr, arguments); // finally call the callback supplied
return res;
}
});
}
希望这是有用的:)
发布于 2012-11-10 23:54:32
我发现以下代码似乎可以实现这一点:https://github.com/mennovanslooten/Observable-Arrays
Observable-Arrays扩展了下划线,可以使用如下方式:(从该页面)
// For example, take any array:
var a = ['zero', 'one', 'two', 'trhee'];
// Add a generic observer function to that array:
_.observe(a, function() {
alert('something happened');
});
https://stackoverflow.com/questions/5100376
复制