我正在尝试将当前的Angular.js项目迁移到Aurelia.js.
我正在尝试做类似的事情:
我正在尝试做类似的事情:
report.js
export class Report { list = []; //TODO listChanged(newList,oldList){ enter code here } }
report.html
<template> <require from="component"></require> <component list.bind="list"></component> </template>
所以问题是:如何检测列表何时更改?
在Angular.js我能做到
$scope.$watchCollection('list',(newVal,oldVal)=>{ my code });
也许Aurelia有类似的东西?
解决方法
对于@bindable字段,只要更新列表值,就会调用listChanged(newValue,oldValue).请看看
Aurelia docs
@customAttribute('if') @templateController export class If { constructor(viewFactory,viewSlot){ // } valueChanged(newValue,oldValue){ // } }
您也可以按照Aurelia作者的博客文章here中的描述使用ObserveLocator:
import {ObserverLocator} from 'aurelia-binding'; // or 'aurelia-framework' @inject(ObserverLocator) class Foo { constructor(observerLocator) { // the property we'll observe: this.bar = 'baz'; // subscribe to the "bar" property's changes: var subscription = this.observerLocator .getObserver(this,'bar') .subscribe(this.onChange); } onChange(newValue,oldValue) { alert(`bar changed from ${oldValue} to ${newValue}`); } }
UPD
正如Jeremy Danyow在this question中所提到的:
The ObserverLocator is Aurelia’s internal “bare Metal” API. There’s now a public API for the binding engine that could be used:
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(); } }
最好的问候,亚历山大