[英]Aurelia make bindable act as observable on object properties
在Aurelia綁定中,如果在組件中我們在屬性上使用可觀察的裝飾,並且如果屬性是對象,那么我們將訂閱該對象的所有屬性。
例如:
import { observable } from 'aurelia-framework';
export class Car {
@observable color = {rgb: '', hex: ''};
colorChanged(newValue, oldValue) {
// this will fire whenever the 'color' property changes
}
}
因此,如果其中一個顏色屬性發生變化,那么它將觸發colorChanged。 但在自定義元素中,我們有這樣的可綁定:
import {bindable, bindingMode} from 'aurelia-framework';
export class SecretMessageCustomElement {
@bindable data;
dataChanged () {
// -------
}
}
然后不會在其屬性更改時調用dataChanged。 怎么解決這個問題?
這是一個例子: https : //gist.run/?id = 040775f06aba5e955afd362ee60863aa
@observable color = { rgb: '', hex: '' }
colorChanged(val) { }
僅當重新分配整個顏色屬性時,rgb或十六進制更改時才會更改colorChanged
。
經過一些嘗試,我編寫了一些代碼來修復我的問題並希望幫助其他人。 我已經訂閱並取消訂閱每次發生的數據更改,並且每次都在每個字段上完成此訂閱。 所以這是解決方案:
import {
bindable,
BindingEngine
} from 'aurelia-framework';
@inject(Element, BindingEngine)
export class PaChartjs {
@bindable data;
@bindable options;
constructor(element, bindingEngine) {
this.element = element;
this.bindingEngine = bindingEngine;
}
bind() {
this.observeObject(this.data, 'data');
this.observeObject(this.options, 'options');
}
unbind() {
this.unobserveObjects();
}
unobserveObjects(groups) {
let self = this;
if (!groups) {
groups = Object.keys(this.subscriptions);
}
groups.forEach((groupitem, groupindex) => {
this.subscriptions[groupitem].forEach((subitem, subindex) => {
subitem.sub.dispose();
delete self.subscriptions[subindex];
}); //otherwise you'll bind twice next time
});
}
observeObject(obj, group) {
let self = this;
if (!this.subscriptions) {
this.subscriptions = [];
}
if (!this.subscriptions[group]) {
this.subscriptions[group] = [];
}
Object.keys(obj).forEach((keyitem, keyindex) => {
if (typeof obj[keyitem] === 'object' && obj[keyitem] !== null) {
self.observeObject(obj[keyitem]);
} else {
this.subscriptions[group].push({
obj: obj,
property: keyitem,
sub: this.bindingEngine
.propertyObserver(obj, keyitem) //e.g. subscribe to obj
.subscribe(() => this.objectPropertyChanged()) //subscribe to prop change
});
}
});
}
objectPropertyChanged(newValue, oldValue) {
this.heavyJobHandler(() => this.updateChartData());
}
dataChanged(newValue, oldValue) {
this.unobserveObjects(['data']);
if (this.chartObj) {
this.chartObj.data = newValue;
this.heavyJobHandler(() => this.updateChartData());
}
this.observeObject(this.data, 'data');
}
optionsChanged(newValue, oldValue) {
this.unobserveObjects(['data']);
if (this.chartObj) {
this.chartObj.options = options;
this.heavyJobHandler(() => this.updateChartData());
}
this.observeObject(this.options, 'options');
}
}
雖然這是代碼的一部分,但它有一個主要的想法。 TG。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.