Matthew James Davis Matthew James Davis - 9 months ago 187
Javascript Question

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?


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'

export class Foo {
    constructor(observerLocator) {
        this.observerLocator = observerLocator;

You can then do something like this:

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

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


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'

export class ViewModel {
  constructor(bindingEngine) {
    this.obj = { foo: 'bar' };

    // subscribe
    let subscription = bindingEngine.propertyObserver(this.obj, 'foo')
      .subscribe((newValue, oldValue) => console.log(newValue));

    // unsubscribe