Aurelia是否有AngularJS $手表替代品?

Ego*_*ich 8 javascript angularjs aurelia aurelia-binding

我正在尝试将当前的Angular.js项目迁移到Aurelia.js.我正在尝试这样做:

report.js

export class Report {
       list = [];

       //TODO
       listChanged(newList, oldList){
             enter code here
       }
}
Run Code Online (Sandbox Code Playgroud)

report.html

<template>
    <require from="component"></require>
    <component list.bind="list"></component>
</template>
Run Code Online (Sandbox Code Playgroud)

所以问题是:如何检测列表何时更改?

在Angular.js我能做到

$scope.$watchCollection('list', (newVal, oldVal)=>{ my code });
Run Code Online (Sandbox Code Playgroud)

也许Aurelia有类似的东西?

Ale*_*nko 9

对于@bindable字段,listChanged(newValue, oldValue)只要list更新值,就会调用它.请看看Aurelia的文档

@customAttribute('if')
@templateController
export class If {
  constructor(viewFactory, viewSlot){
    //
  }

  valueChanged(newValue, oldValue){
    //
  }
}
Run Code Online (Sandbox Code Playgroud)

你也可以用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}`);
  }
}
Run Code Online (Sandbox Code Playgroud)

UPD

正如Jeremy Danyow 在这个问题中所提到的:

ObserverLocator是Aurelia的内部"裸机"API.现在有一个可以使用的绑定引擎的公共API:

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();
  }
}
Run Code Online (Sandbox Code Playgroud)

此致,亚历山大


Jer*_*yow 7

您的原始代码将使用一个小调整:

report.js

import {bindable} from 'aurelia-framework'; // or 'aurelia-binding'

export class Report {
       @bindable list;  // decorate the list property with "bindable"

       // Aurelia will call this automatically
       listChanged(newList, oldList){
             enter code here
       }
}
Run Code Online (Sandbox Code Playgroud)

report.html

<template>
    <require from="component"></require>
    <component list.bind="list"></component>
</template>
Run Code Online (Sandbox Code Playgroud)

Aurelia有一个约定,它将[propertyName]Changed在您的viewmodel上查找一个方法并自动调用它.此约定与所有使用的属性一起使用@bindable.更多信息在这里