如何监视数组的变化?

在 Javascript 中,当使用 push、 pop、 shift 或基于索引的赋值修改数组时,是否有通知方式?我想要一些我能处理的事件。

我知道 SpiderMonkey 中的 watch()功能,但是只有当整个变量被设置为其他值时,它才能工作。

140034 次浏览

有几个选择。

1. 重写 push 方法

通过快速而简单的方法,您可以覆盖数组 1push()方法:

Object.defineProperty(myArray, "push", {
// hide from for..in and prevent further overrides (via default descriptor values)
value: function () {
for (var i = 0, n = this.length, l = arguments.length; i < l; i++, n++) {
RaiseMyEvent(this, n, this[n] = arguments[i]); // assign/raise your event
}
return n;
}
});

或者,如果您想要针对 所有数组,您可以覆盖 Array.prototype.push()。但是,请谨慎使用; 您环境中的其他代码可能不喜欢或不希望进行这种修改。尽管如此,如果一个包罗万象的方法听起来很吸引人,只要用 Array.prototype代替 myArray即可。

现在,这只是一个方法,有很多方法可以更改数组内容。我们可能需要更全面的..。

2. 创建一个自定义的可观察数组

您可以创建自己的可观察数组,而不是重写方法。这个特殊的实现将一个数组复制到一个新的类似数组的对象中,并提供定制的 push()pop()shift()unshift()slice()splice()方法 还有定制索引访问器(前提是数组大小仅通过上述方法之一或 length属性修改)。

function ObservableArray(items) {
var _self = this,
_array = [],
_handlers = {
itemadded: [],
itemremoved: [],
itemset: []
};


function defineIndexProperty(index) {
if (!(index in _self)) {
Object.defineProperty(_self, index, {
configurable: true,
enumerable: true,
get: function() {
return _array[index];
},
set: function(v) {
_array[index] = v;
raiseEvent({
type: "itemset",
index: index,
item: v
});
}
});
}
}


function raiseEvent(event) {
_handlers[event.type].forEach(function(h) {
h.call(_self, event);
});
}


Object.defineProperty(_self, "addEventListener", {
configurable: false,
enumerable: false,
writable: false,
value: function(eventName, handler) {
eventName = ("" + eventName).toLowerCase();
if (!(eventName in _handlers)) throw new Error("Invalid event name.");
if (typeof handler !== "function") throw new Error("Invalid handler.");
_handlers[eventName].push(handler);
}
});


Object.defineProperty(_self, "removeEventListener", {
configurable: false,
enumerable: false,
writable: false,
value: function(eventName, handler) {
eventName = ("" + eventName).toLowerCase();
if (!(eventName in _handlers)) throw new Error("Invalid event name.");
if (typeof handler !== "function") throw new Error("Invalid handler.");
var h = _handlers[eventName];
var ln = h.length;
while (--ln >= 0) {
if (h[ln] === handler) {
h.splice(ln, 1);
}
}
}
});


Object.defineProperty(_self, "push", {
configurable: false,
enumerable: false,
writable: false,
value: function() {
var index;
for (var i = 0, ln = arguments.length; i < ln; i++) {
index = _array.length;
_array.push(arguments[i]);
defineIndexProperty(index);
raiseEvent({
type: "itemadded",
index: index,
item: arguments[i]
});
}
return _array.length;
}
});


Object.defineProperty(_self, "pop", {
configurable: false,
enumerable: false,
writable: false,
value: function() {
if (_array.length > -1) {
var index = _array.length - 1,
item = _array.pop();
delete _self[index];
raiseEvent({
type: "itemremoved",
index: index,
item: item
});
return item;
}
}
});


Object.defineProperty(_self, "unshift", {
configurable: false,
enumerable: false,
writable: false,
value: function() {
for (var i = 0, ln = arguments.length; i < ln; i++) {
_array.splice(i, 0, arguments[i]);
defineIndexProperty(_array.length - 1);
raiseEvent({
type: "itemadded",
index: i,
item: arguments[i]
});
}
for (; i < _array.length; i++) {
raiseEvent({
type: "itemset",
index: i,
item: _array[i]
});
}
return _array.length;
}
});


Object.defineProperty(_self, "shift", {
configurable: false,
enumerable: false,
writable: false,
value: function() {
if (_array.length > -1) {
var item = _array.shift();
delete _self[_array.length];
raiseEvent({
type: "itemremoved",
index: 0,
item: item
});
return item;
}
}
});


Object.defineProperty(_self, "splice", {
configurable: false,
enumerable: false,
writable: false,
value: function(index, howMany /*, element1, element2, ... */ ) {
var removed = [],
item,
pos;


index = index == null ? 0 : index < 0 ? _array.length + index : index;


howMany = howMany == null ? _array.length - index : howMany > 0 ? howMany : 0;


while (howMany--) {
item = _array.splice(index, 1)[0];
removed.push(item);
delete _self[_array.length];
raiseEvent({
type: "itemremoved",
index: index + removed.length - 1,
item: item
});
}


for (var i = 2, ln = arguments.length; i < ln; i++) {
_array.splice(index, 0, arguments[i]);
defineIndexProperty(_array.length - 1);
raiseEvent({
type: "itemadded",
index: index,
item: arguments[i]
});
index++;
}


return removed;
}
});


Object.defineProperty(_self, "length", {
configurable: false,
enumerable: false,
get: function() {
return _array.length;
},
set: function(value) {
var n = Number(value);
var length = _array.length;
if (n % 1 === 0 && n >= 0) {
if (n < length) {
_self.splice(n);
} else if (n > length) {
_self.push.apply(_self, new Array(n - length));
}
} else {
throw new RangeError("Invalid array length");
}
_array.length = n;
return value;
}
});


Object.getOwnPropertyNames(Array.prototype).forEach(function(name) {
if (!(name in _self)) {
Object.defineProperty(_self, name, {
configurable: false,
enumerable: false,
writable: false,
value: Array.prototype[name]
});
}
});


if (items instanceof Array) {
_self.push.apply(_self, items);
}
}


(function testing() {


var x = new ObservableArray(["a", "b", "c", "d"]);


console.log("original array: %o", x.slice());


x.addEventListener("itemadded", function(e) {
console.log("Added %o at index %d.", e.item, e.index);
});


x.addEventListener("itemset", function(e) {
console.log("Set index %d to %o.", e.index, e.item);
});


x.addEventListener("itemremoved", function(e) {
console.log("Removed %o at index %d.", e.item, e.index);
});
 

console.log("popping and unshifting...");
x.unshift(x.pop());


console.log("updated array: %o", x.slice());


console.log("reversing array...");
console.log("updated array: %o", x.reverse().slice());


console.log("splicing...");
x.splice(1, 2, "x");
console.log("setting index 2...");
x[2] = "foo";


console.log("setting length to 10...");
x.length = 10;
console.log("updated array: %o", x.slice());


console.log("setting length to 2...");
x.length = 2;


console.log("extracting first element via shift()");
x.shift();


console.log("updated array: %o", x.slice());


})();

请参阅 Object.defineProperty()

这让我们更接近了,但还是不能防弹,这就让我们想到:

3. 代理服务器

代理对象为 现代的浏览器提供了另一种解决方案。它允许您拦截方法调用、访问器等。最重要的是,您甚至可以在不提供显式属性名的情况下完成此操作... ... 这将允许您测试任意的、基于索引的访问/赋值。您甚至可以拦截属性删除。代理将有效地允许您检查 之前决定允许的更改... ... 除了在事后处理更改之外。

下面是一个精简的样本:

(function() {


if (!("Proxy" in window)) {
console.warn("Your browser doesn't support Proxies.");
return;
}


// our backing array
var array = ["a", "b", "c", "d"];


// a proxy for our array
var proxy = new Proxy(array, {
deleteProperty: function(target, property) {
delete target[property];
console.log("Deleted %s", property);
return true;
},
set: function(target, property, value, receiver) {
target[property] = value;
console.log("Set %s to %o", property, value);
return true;
}
});


console.log("Set a specific index..");
proxy[0] = "x";


console.log("Add via push()...");
proxy.push("z");


console.log("Add/remove via splice()...");
proxy.splice(1, 3, "y");


console.log("Current state of array: %o", array);


})();

我发现以下几点似乎可以达到这个目的: Https://github.com/mennovanslooten/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');
});

我不建议您扩展本机原型。相反,您可以使用一个类似 new-list 的库; https://github.com/azer/new-list

它创建了一个本地 JavaScript 数组,允许您订阅任何更改。它批量更新,并给你最终的差异;

List = require('new-list')
todo = List('Buy milk', 'Take shower')


todo.pop()
todo.push('Cook Dinner')
todo.splice(0, 1, 'Buy Milk And Bread')


todo.subscribe(function(update){ // or todo.subscribe.once


update.add
// => { 0: 'Buy Milk And Bread', 1: 'Cook Dinner' }


update.remove
// => [0, 1]


})
if (!Array.prototype.forEach)
{
Object.defineProperty(Array.prototype, 'forEach',
{
enumerable: false,
value: function(callback)
{
for(var index = 0; index != this.length; index++) { callback(this[index], index, this); }
}
});
}


if(Object.observe)
{
Object.defineProperty(Array.prototype, 'Observe',
{
set: function(callback)
{
Object.observe(this, function(changes)
{
changes.forEach(function(change)
{
if(change.type == 'update') { callback(); }
});
});
}
});
}
else
{
Object.defineProperties(Array.prototype,
{
onchange: { enumerable: false, writable: true, value: function() { } },
Observe:
{
set: function(callback)
{
Object.defineProperty(this, 'onchange', { enumerable: false, writable: true, value: callback });
}
}
});


var names = ['push', 'pop', 'reverse', 'shift', 'unshift'];
names.forEach(function(name)
{
if(!(name in Array.prototype)) { return; }
var pointer = Array.prototype[name];
Array.prototype[name] = function()
{
pointer.apply(this, arguments);
this.onchange();
}
});
}


var a = [1, 2, 3];
a.Observe = function() { console.log("Array changed!"); };
a.push(8);

一个有趣的集合库是 https://github.com/mgesmundo/smart-collection。允许您观察数组并向它们添加视图。我不确定性能,因为我正在测试它自己。将很快更新这篇文章。

通过阅读这里的所有答案,我已经组装了一个不需要任何外部库的简化解决方案。

它还更好地说明了这种方法的总体思路:

function processQ() {
// ... this will be called on each .push
}


var myEventsQ = [];
myEventsQ.push = function() { Array.prototype.push.apply(this, arguments);  processQ();};

我使用以下代码侦听对数组的更改。

/* @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;
}
});
}

希望这个有用:)

不确定这是否涵盖了所有内容,但我使用类似的方法(特别是在调试时)来检测数组是否添加了元素:

var array = [1,2,3,4];
array = new Proxy(array, {
set: function(target, key, value) {
if (Number.isInteger(Number(key)) || key === 'length') {
debugger; //or other code
}
target[key] = value;
return true;
}
});

我把玩了一下,然后想出了这个。其思想是,该对象定义了所有 Array.雏形方法,但是在一个单独的数组对象上执行它们。这使得我们能够观察 shift ()、 pop ()等方法。尽管一些方法(如 concat ())不会返回 OArray 对象。如果使用了访问器,那么重载这些方法不会使对象变得可观察。为了实现后者,在给定的容量内为每个索引定义访问器。

性能方面... OArray 比普通 Array 对象慢10-25倍。对于1-100范围内的容量,差值为1 x-3 x。

class OArray {
constructor(capacity, observer) {


var Obj = {};
var Ref = []; // reference object to hold values and apply array methods


if (!observer) observer = function noop() {};


var propertyDescriptors = Object.getOwnPropertyDescriptors(Array.prototype);


Object.keys(propertyDescriptors).forEach(function(property) {
// the property will be binded to Obj, but applied on Ref!


var descriptor = propertyDescriptors[property];
var attributes = {
configurable: descriptor.configurable,
enumerable: descriptor.enumerable,
writable: descriptor.writable,
value: function() {
observer.call({});
return descriptor.value.apply(Ref, arguments);
}
};
// exception to length
if (property === 'length') {
delete attributes.value;
delete attributes.writable;
attributes.get = function() {
return Ref.length
};
attributes.set = function(length) {
Ref.length = length;
};
}


Object.defineProperty(Obj, property, attributes);
});


var indexerProperties = {};
for (var k = 0; k < capacity; k++) {


indexerProperties[k] = {
configurable: true,
get: (function() {
var _i = k;
return function() {
return Ref[_i];
}
})(),
set: (function() {
var _i = k;
return function(value) {
Ref[_i] = value;
observer.call({});
return true;
}
})()
};
}
Object.defineProperties(Obj, indexerProperties);


return Obj;
}
}

@ canon 推荐最多的 重写推送方法解决方案有一些副作用,这些副作用对我来说是不方便的:

  • 它使得 push 属性描述符不同(应该将 writableconfigurable设置为 true而不是 false) ,这会导致以后出现异常。

  • 当使用多个参数(如 myArray.push("a", "b"))一次调用 push()时,它会多次引发该事件,在我的例子中,这是不必要的,并且不利于性能。

因此,这是我能找到的解决以前问题的最佳方案,在我看来,它更干净、更简单、更容易理解。

Object.defineProperty(myArray, "push", {
configurable: true,
enumerable: false,
writable: true, // Previous values based on Object.getOwnPropertyDescriptor(Array.prototype, "push")
value: function (...args)
{
let result = Array.prototype.push.apply(this, args); // Original push() implementation based on https://github.com/vuejs/vue/blob/f2b476d4f4f685d84b4957e6c805740597945cde/src/core/observer/array.js and https://github.com/vuejs/vue/blob/daed1e73557d57df244ad8d46c9afff7208c9a2d/src/core/util/lang.js


RaiseMyEvent();


return result; // Original push() implementation
}
});

请参阅我的源代码的评论,以及关于如何实现除了 push 之外的其他变异功能的提示: ‘ pop’、‘ shift’、‘ unshift’、‘ splice’、‘ sort’、‘ return’。