如何观察阵列变化?

Sri*_*ala 88 javascript dom-events

在Javascript中,有没有办法在使用push,pop,shift或基于索引的赋值修改数组时收到通知?我想要一些可以触发我能处理的事件的东西.

我知道SpiderMonkey中的watch()功能,但只有当整个变量设置为其他内容时才有效.

I a*_*ica 146

有几个选择......

1.覆盖推送方法

走快速而肮脏的路线,您可以覆盖push()阵列1的方法:

Object.defineProperty(myArray, "push", {
  enumerable: false, // hide from for...in
  configurable: false, // prevent further meddling...
  writable: false, // see above ^
  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;
  }
});
Run Code Online (Sandbox Code Playgroud)

1或者,如果您想要定位所有阵列,则可以覆盖Array.prototype.push().但请谨慎使用; 您环境中的其他代码可能不喜欢或期望这种修改.尽管如此,如果一个人都听起来很有吸引力,那就换myArray一下吧Array.prototype.

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

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

})();
Run Code Online (Sandbox Code Playgroud)

参见参考.Object.defineProperty()

这让我们更接近,但它仍然不是防弹...这带来了我们:

3.代理人

在未来1,代理可以提供另一种解决方案......允许您拦截方法调用,访问器等.最重要的是,您甚至可以在不提供显式属性名称的情况下执行此操作...这将允许您测试任意,基于索引的访问/分配.你甚至可以截取属性删除.代理将有效地允许您决定允许之前检查更改...除了在事后处理更改之外.

这是一个精简的样本:

(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, {
    apply: function(target, thisArg, argumentsList) {
      return thisArg[target].apply(this, argumentList);
    },
    deleteProperty: function(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);

})();
Run Code Online (Sandbox Code Playgroud)

1 浏览器支持越来越好,但仍有一些明显的漏洞.

  • 将Array子类化得更好.修改Array的原型通常不是一个好主意. (8认同)
  • 我想你可以在Array的原型中实现一个方法`set(index)`并做一些类似反义的说法 (4认同)
  • 这里有出色的答案。ObservableArray 的类非常出色。+1 (2认同)

Syc*_*ych 16

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

它还说明了该方法的总体思路:

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

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

  • “push”返回数组的“length”。因此,您可以将“Array.prototype.push.apply”返回的值获取到变量,并从自定义“push”函数返回它。 (4认同)
  • 你不明白解决方案。myEventsQ 是数组(您的 50 个数组之一)。这段代码没有改变数组的大小,也没有添加任何额外的数组,它只是改变了现有数组的原型。 (2认同)
  • 嗯,我明白了,不过应该提供更多解释! (2认同)

小智 12

我发现以下内容似乎可以做到这一点: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');
});
Run Code Online (Sandbox Code Playgroud)

  • 这很好,但有一个重要的警告:当一个数组被修改为`arr [2] ="foo"`时,更改通知是_asynchronous_.由于JS没有提供任何监视此类更改的方法,因此该库依赖于每250毫秒运行一次的超时并检查数组是否已更改 - 因此在下一个更新之前您不会收到更改通知超时运行的时间.然而,诸如`push()`之类的其他更改会立即(同步)得到通知. (11认同)
  • 此外,如果阵列很大,我猜250间隔会影响您的网站性能. (5认同)

Nad*_*kar 12

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

/* @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;
                 }
    });
}
Run Code Online (Sandbox Code Playgroud)

希望这是有用的:)


cpr*_*ack 7

@canon 最受好评的Override push 方法解决方案有一些副作用,对我来说很不方便:

  • 它使 push 属性描述符不同(writable并且configurable应该设置true而不是false),这会导致稍后出现异常。

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

所以这是我能找到的最好的解决方案,它解决了以前的问题,在我看来更清晰/更简单/更容易理解。

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
    }
});
Run Code Online (Sandbox Code Playgroud)

请参阅我的来源的评论以及有关如何实现除 push 之外的其他变异函数的提示:'pop'、'shift'、'unshift'、'splice'、'sort'、'reverse'。