jme*_*zel 4 javascript binding aurelia
当绑定对象中发生更新时,我想得到通知。这个 plunk http://plnkr.co/edit/7thr0V演示了我的问题。
更详细地说:我通过 bind [data.bind] 将对象“数据”传递到自定义元素中。如果我现在更新数据中的一个属性,我希望自定义元素中的“dataChanged”钩子被调用。如果我在自定义元素模板中显示绑定数据对象的属性,它会更新,因此绑定本身可以正常工作。
我的第二个责备是使用 ObserverLocator,但它也不会触发嵌套更新。
app.js 中的对象:
this.data = {
nested: {
content: "Hello nested world!"
}
};
Run Code Online (Sandbox Code Playgroud)
自定义元素ce的绑定:
<require from="ce"></require>
<ce data.bind="data"></ce>
Run Code Online (Sandbox Code Playgroud)
ce.js 部分:
@bindable data;
constructor(observerLocator) {
this.observerLocator = observerLocator;
var subscription = this.observerLocator
.getObserver(this, 'data')
//.getObserver(this, 'data["nested"]["content"]') //Doesn't work
//.getObserver(this, 'data.nested.content') //Doesn't work
.subscribe(this.onChangeData);
}
onChangeData(newData, oldData) {
console.log('data changed from ', oldData, newData);
}
dataChanged(d) {
console.log("Changed", d);
}
Run Code Online (Sandbox Code Playgroud)
ce模板部分:
${data.nested.content}
Run Code Online (Sandbox Code Playgroud)
在 app.js 中,我以 2 个间隔更新数据对象。第一个间隔每秒编辑一个“嵌套”属性。每五秒的第二个间隔将数据对象设置为新的。在第二个间隔,钩子和观察者被调用,但我想知道,当第一个间隔发生任何变化时。
setInterval(() => {
this.data.nested.content += "!";
}, 1000);
setInterval(() => {
this.data = {
nested: {
content: "Hello nested world No. " + this.counter++ + "!"
}
};
}, 5000);
Run Code Online (Sandbox Code Playgroud)
的ObserverLocator是奥里利亚的用于观察简单属性更改和阵列/图/组突变裸机API。
有一个名为 的新的更高级别的 API BindingEngine,您可以使用它来观察复杂的表达式。
这是一个例子:https : //gist.run?id=868a7611952b2e40f350
ce.html
<template>
${data.nested.content}
<!-- debug logging -->
<h4>Observed Changes:</h4>
<div repeat.for="change of changes"><pre><code>${change}</code></pre></div>
</template>
Run Code Online (Sandbox Code Playgroud)
ce.js
import {
bindable,
BindingEngine,
inject
} from "aurelia-framework";
@inject(BindingEngine)
export class Ce {
@bindable data;
changes = []; // debug logging
constructor(bindingEngine) {
this.bindingEngine = bindingEngine;
}
expressionChanged(newValue, oldValue) {
// debug logging:
this.changes.splice(0, 0, `expressionChanged: "${newValue}"`);
}
syncSubscription(subscribe) {
if (this.subscription) {
this.subscription.dispose();
this.subscription = null;
}
if (subscribe && this.data) {
let observer = this.bindingEngine.expressionObserver(this.data, 'nested.content');
this.subscription = observer.subscribe(::this.expressionChanged);
}
}
dataChanged(newValue, oldValue) {
// subscribe to new data instance
this.syncSubscription(true);
// debug logging:
this.changes.splice(0, 0, `dataChanged: ${JSON.stringify(newValue, null, 2)}`);
}
attached() {
// subscribe
this.syncSubscription(true);
}
detached() {
// unsubscribe (avoid memory leaks)
this.syncSubscription(false);
}
}
Run Code Online (Sandbox Code Playgroud)
为什么 aurelia 默认不观察整个对象的变化?
就速度和内存而言,急切地观察一切都太昂贵了。并非所有浏览器都支持 object.observe。
| 归档时间: |
|
| 查看次数: |
2210 次 |
| 最近记录: |