Aurelia中的数组订阅 [英] Array subscription in Aurelia

查看:73
本文介绍了Aurelia中的数组订阅的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一系列元素,除了在我的应用程序中显示列表外,我还希望使用 HttpClient 将列表同步到服务器。如何观察阵列的变化?我试过了:

Let's say I have an array of elements and in addition to displaying the list in my app, I want to sync the list to the server with HttpClient. How can I observe changes to the array? I tried:

@inject(ObserverLocator)
export class ViewModel {

    constructor(obsLoc) {
        this.list = [];
        obsLoc.getObserver(this, 'list');
            .subscribe(li => console.log(li));
    }
}

但我既没有错误也没有记录消息。

But I got neither error nor log message.

推荐答案

getObserver 返回一个属性观察者,它会在<$ c时通知你$ c> ViewModel 类实例的列表属性更改。这只会在您为列表属性分配新值时发生,即 this.list = [1,2,3] 。如果您没有为列表属性分配新值,而是通过 push 来改变属性的值, pop splice 等,您将要使用数组观察者。使用 ObserverLocator getArrayObserver 方法 - 它需要一个参数,即你想要观察的数组:

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));
    }
}



2015年10月更新



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

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();
  }
}

这篇关于Aurelia中的数组订阅的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆