Aurelia观察者未触发阵列

LSt*_*rky 5 aurelia aurelia-binding

我有一个简化的自定义数据网格元素,如下所示:

export class DataGrid {

  @bindable data;

  dataChanged(newValue, oldValue) {
    console.log("Sensing new data...", newValue);
  }
}
Run Code Online (Sandbox Code Playgroud)

实例化如下:

<data-grid data.bind="records"></data-grid>
Run Code Online (Sandbox Code Playgroud)

出现数据网格时,控制台中将显示“正在检测新数据...”和记录数组。但是,当我从对象数组中删除一条记录时,dataChanged()不会触发该函数。

let index = this.records.findIndex((r) => { return r.acc_id === this.record.acc_id; });
if (index > -1) {
  console.log("Deleting element..." + index, this.records);
  this.records.splice(index, 1);
}
Run Code Online (Sandbox Code Playgroud)

我在控制台中看到“正在删除元素...”,但没有看到“正在检测新数据...”

有什么想法为什么dataChanged()我在拼接唱片时不开火?

Tra*_*avo 5

您无法观察到类似这样的突变的数组。您必须改为使用collectionObserver。现在,dataChanged()仅当您覆盖该data值(即data = [1, 2, 3]使用新数组覆盖该值)时,您才会触发。


例如如何使用collectionObserverBindingEngine类,为您的用例。

import { BindingEngine } from 'aurelia-framework';

export class DataGrid {
  static inject = [BindingEngine];

  @bindable data;

  constructor(bindingEngine) {
    this._bindingEngine = bindingEngine;
  }

  attached() {
    this._dataObserveSubscription = this._bindingEngine
      .collectionObserver(this.data)
      .subscribe(splices => this.dataArrayChanged(splices));
  }

  detached() {
    // clean up this observer when the associated view is removed
    this._dataObserveSubscription.dispose();
  }


  dataArrayChanged(splices) {
    console.log('Array mutated', splices);
  }
}
Run Code Online (Sandbox Code Playgroud)