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

查看:23
本文介绍了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 返回一个属性观察者,当 ViewModel 类实例的 list 属性更改.这只会在您为 list 属性分配新值时发生,即 this.list = [1,2,3].如果您没有为 list 属性分配新值,而是通过 pushpop 改变属性的值splice 等,您将需要使用数组观察器.使用 ObserverLocatorgetArrayObserver 方法——它需要一个参数,你想观察的数组:

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天全站免登陆