使用 Aurelia 订阅属性更改

IT技术 javascript ecmascript-6 aurelia
2021-03-13 00:31:30

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

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

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

4个回答

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

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

然后你可以做这样的事情:

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

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

subscription();

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

更多信息在这里

2015 年 10 月更新

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

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 的 Event Aggregator 功能吗?
2021-04-24 00:31:30
@jeremy-danyow propertyObserver 和 expressionObserver 有什么区别?
2021-05-05 00:31:30
@ChiRow 请不要滥用 EventAggregator!它可以在这种情况下使用,但通常情况下,如果您正在考虑订阅者,您正在考虑紧密耦合的行为,而 EventAggregator 则用于松散耦合的行为。
2021-05-09 00:31:30
propertyObserver观察特定属性(例如firstName)并在属性更改时通知您。 expressionObserver观察整个表达式(例如foo.bar[x][baz].hello() * test / something)并在表达式的结果发生变化时通知您。
2021-05-17 00:31:30
@jeremy-danyow 干得好,不要忘记在 api 更改时更新它:)
2021-05-20 00:31:30

根据I kill nerds, observable 属性对绑定的开销较小

import {observable} from "aurelia-framework";

export class Example {

    @observable
    public description: string;

    private descriptionChanged(newValue: string, oldValue: string): void {

    }
}

根据其值侦听和触发事件

使用 TypeScript 的代码片段,希望能让您有所了解:

import {bindingMode} from "aurelia-binding";

export class Example{

    @bindable
    public description: string;

    private descriptionChanged(newValue: string, oldValue: string): void {
        console.log(newValue, oldValue);
    }
}

方法名称应遵循约定 `${propertyName}Changed`


编辑:这正是Decade Moon在上面的评论中所建议的:Property change subscription with Aurelia

它有效,因为 description 是一个字符串。上面的方法不适用于对象和数组,就像最初提出的问题一样。我所知道的。
2021-05-10 00:31:30
我最喜欢这个解决方案。它使用更少的代码来完成相同的任务。
2021-05-21 00:31:30

@observable装饰工作正常,这种情况下。

您可以使用BindingEngine来观看收藏或控制何时订阅/取消订阅