Aurelia - 观察变化的依赖值

时间:2016-02-05 18:45:32

标签: aurelia

假设您有一个正在注入另一个类或组件的类。有没有办法观察你注入的依赖关系的归因变化并对其采取行动?

例如,假设您有以下应用:

app.html

<template>
  <input type="text" value.bind="item">
  <button click.trigger="addToList()">Add</button>

  <h3>Modded</h3>
  <ul>
    <li repeat.for="it of modded">${it}</li>
  </ul>

  <h3>Original</h3>
  <ul>
    <li repeat.for="it of dep.items">${it}</li>
  </ul>
</template>

app.js

import {bindable, inject} from 'aurelia-framework';
import {Dep} from './dep';

@inject(Dep)
export class App {
  constructor(dep) {
    this.dep = dep;
  }

  attached() {
    this.modifyItems();
  }

  addToList() {
    this.dep.addItem(this.item);
  }

  modifyItems() {
    this.modded = [];
    for (let item of this.dep.items) {
      this.modded.push(item.toUpperCase());
    }
  }
}

dep.js

export class Dep {
  constructor() {
    this.items = ['one', 'two', 'three'];
  }

  addItem(item) {
    this.items.push(item);
  }
}

现在,让我们说其他一些组件修改Dep.items。有没有办法在app.js this.dep.items上关注modifyItems(),然后拨打modifyItems()

假设<div ng-app="app" ng-controller='myCtrl as vm'> <button ng-click="$root.page = 1">Change root Page</button> <label> showSelectOnly: {{showSelectOnly}} </label> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js"></script> 比此示例更复杂,因此值转换器可能不是最佳选择。 (除非这是我猜的唯一选择)

以下是上面例子:http://plnkr.co/edit/rEs9UM?p=preview

1 个答案:

答案 0 :(得分:3)

有人把我指向BindingEngine.collectionObserver,看来这就是我需要的。

app.js:

import {inject} from 'aurelia-framework';
import {BindingEngine} from 'aurelia-binding';
import {Dep} from './dep';

@inject(Dep, BindingEngine)
export class App {
  constructor(dep, bindingEngine) {
    this.dep = dep;

    let subscription = bindingEngine.collectionObserver(this.dep.items)
      .subscribe((newVal, oldVal) => {
        console.debug(newVal, oldVal);
        this.modifyItems();
      });
  }

  attached() {
    this.modifyItems();
  }

  addToList() {
    this.dep.addItem(this.item);
    this.item = '';
  }

  modifyItems() {
    this.modded = [];
    for (let item of this.dep.items) {
      this.modded.push(item.toUpperCase());
    }
  }
}

以下是工作插件:http://plnkr.co/edit/Pcyxrh?p=preview