我的视图模型上有一个属性,我想根据其值监听并触发事件,如下所示:
class viewModel {
constructor() {
this.value = '0';
let val = 2;
subscribe(this.value, callbackForValue);
subscribe(val, callbackForVal);
}
}
这是Aurelia的特色吗?如果是这样,我将如何设置这样的订阅?
在一些插件中我一直在使用 DI 来获取ObserverLocator
来自容器的实例:
import {inject} from 'aurelia-dependency-injection'; // or from 'aurelia-framework'
import {ObserverLocator} from 'aurelia-binding'; // or from 'aurelia-framework'
@inject(ObserverLocator)
export class Foo {
constructor(observerLocator) {
this.observerLocator = observerLocator;
}
...
}
然后你可以做这样的事情:
var subscription = this.observerLocator
.getObserver(myObj, 'myPropertyName')
.subscribe(myCallback);
当您准备好处理订阅时,调用它:
subscription();
我认为这一切都可能会发生变化,但如果您需要的话,您现在就可以使用它。
更多信息here http://www.danyow.net/aurelia-property-observation/
2015 年 10 月更新
ObserverLocator 是 Aurelia 的内部“裸机”API。现在有一个可以使用的绑定引擎的公共 API:
import {inject} from 'aurelia-dependency-injection'; // or from 'aurelia-framework'
import {BindingEngine} from 'aurelia-binding'; // or from 'aurelia-framework'
@inject(BindingEngine)
export class ViewModel {
constructor(bindingEngine) {
this.obj = { foo: 'bar' };
// subscribe
let subscription = bindingEngine.propertyObserver(this.obj, 'foo')
.subscribe((newValue, oldValue) => console.log(newValue));
// unsubscribe
subscription.dispose();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)