使用 Aurelia 订阅属性更改 [英] Property change subscription with Aurelia

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

问题描述

我的视图模型上有一个属性,我想根据其值侦听并触发事件,如下所示:

I have a property on my viewmodel which I want to listen to and trigger events based on its value, like this:

class viewModel {
  constructor() {
    this.value = '0';
    let val = 2;
    subscribe(this.value, callbackForValue);
    subscribe(val, callbackForVal);
  }
}

这是 Aurelia 的特性吗?如果是这样,我将如何设置此类订阅?

Is this a feature of Aurelia? If so, how would I go about setting up such a subscription?

推荐答案

在一些插件中,我一直使用 DI 从容器中获取 ObserverLocator 实例:

In some plugins I've been using DI to get the ObserverLocator instance from the container:

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

@inject(ObserverLocator)
export class Foo {
    constructor(observerLocator) {
        this.observerLocator = observerLocator;
    }
    ...
}

然后您可以执行以下操作:

You can then do something like this:

var subscription = this.observerLocator
    .getObserver(myObj, 'myPropertyName')
    .subscribe(myCallback);

当您准备好处理订阅时,调用它:

When you're ready to dispose of the subscription, invoke it:

subscription();

我认为这一切都可能发生变化,但如果需要,您现在可以使用它.

I think this is all subject to change but it's something you could use right now if you needed to.

更多信息这里

More info here

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

The ObserverLocator is Aurelia's internal "bare metal" API. There's now a public API for the binding engine that could be used:

import {inject} from 'aurelia-dependency-injection';  // or from 'aurelia-framework'
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();
  }
}

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

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