Array subscription in Aurelia

自作多情 提交于 2019-11-30 01:21:38
Jeremy Danyow

getObserver returns a property observer which will notify you when the ViewModel class instance's list property changes. This will only happen when you assign a new value to the list property, ie this.list = [1,2,3]. If you're not assigning new values to the list property and instead are mutating the value of the property via push, pop, splice, etc, you'll want to use an array observer. Use the ObserverLocator's getArrayObserver method- it takes one parameter, the array you want to observe:

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

@inject(ObserverLocator)
export class ViewModel {

    constructor(obsLoc) {
        this.list = [];
        obsLoc.getArrayObserver(this.list);
            .subscribe(splices => console.log(splices));
    }
}

October 2015 update

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.list = []; // any Array, Map and soon Set will be supported

    // subscribe
    let subscription = bindingEngine.collectionObserver(this.list)
      .subscribe(splices => console.log(splices));

    // be sure to unsubscribe **later**
    subscription.dispose();
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!