35

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

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

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

4

4 回答 4

54

在一些插件中,我一直在使用 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();
  }
}
于 2015-02-10T17:00:42.347 回答
12

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

import {observable} from "aurelia-framework";

export class Example {

    @observable
    public description: string;

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

    }
}
于 2016-09-02T11:43:27.070 回答
10

根据其值监听并触发事件

使用 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

于 2016-07-12T10:28:49.780 回答
2

@observable装饰器适用于这种情况。

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

于 2017-01-05T14:09:08.960 回答