我有一个简化的自定义数据网格元素:
export class DataGrid {
@bindable data;
dataChanged(newValue, oldValue) {
console.log("Sensing new data...", newValue);
}
}
它的实例化如下:
<data-grid data.bind="records"></data-grid>
“感应新数据......”,当数据网格出现时,控制台中会显示记录数组。但是,当我从对象数组中删除记录时,不会触发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);
}
我在控制台中“删除元素...”但“感知新数据......”。
当我拼出记录时,dataChanged()
没有解雇的任何想法?
答案 0 :(得分:5)
你无法观察到像这样的突变的数组。您必须使用collectionObserver
代替。现在,只有覆盖dataChanged()
值(即data
用新数组覆盖它)时,data = [1, 2, 3]
才会触发。
示例如何使用collectionObserver
类中的BindingEngine
作为您的用例:
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);
}
}