如果关键是要知道值何时发生了变化,您需要创建显式设置器和获取器。
正如所建议的,如果可用,Proxy是一个不错的选择。它可能不适用于所有浏览器。在这种情况下,您可以创建一个新对象,在设置时通知您。
这种方法存在很多折衷,而且实现数组本身提供的所有东西都是相当多的工作。下面的例子非常简单,但它确实提供了数组,如交互和setter事件来监听。
var observableArray = function(eventName) {
var myArray = [];
var api = {};
api.get = function(index) {
if (myArray.length && typeof index === 'number') {
return myArray[index];
}
};
api.set = function(item, index) {
if (typeof index === 'number') {
myArray[index] = item;
}
else {
index = myArray.push(item) - 1;
}
var event = new CustomEvent(eventName, {detail: index});
document.dispatchEvent(event);
return index;
};
api.getLength = function() {
return myArray.length;
};
api.empty = function() {
myArray.splice(0, myArray.length);
};
return api;
};
var arrayListener = document.addEventListener('foo', function(e) {console.log('The index modified: ',e.detail);},false);
var test = new observableArray('foo');
test.set('bar');
console.log('The # of items: ', test.getLength());
test.empty();
console.log('The # of items after empty: ', test.getLength());
如果你只需要一种能够使当阵列值设置事情发生,你可以扩展阵列有一个触发回调一套方法。这取决于程序员使用它。
Array.prototype.set = function(item, index, callback) {
if (typeof index === 'number') {
this[index] = item;
}
else {
index = this.push(item) - 1;
}
if (callback) {
callback.apply(this, [index]);
}
return index;
};
var test2 = [];
test2.set('foo', 4, function(i) {
console.log('Callback value: ', i);
console.log('The array: ', this);
});
你的意思只是对于属性“'2'”还是对所有索引? – Bergi
@Bergi所有指数 – user1533299
然后你想要一个代理,是的。另请参见[here](http://stackoverflow.com/a/11523671/1048572) – Bergi