Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

javascript - Property change subscription with 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);
  }
}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...