Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array subscription in Aurelia

Let's say I have an array of elements and in addition to displaying the list in my app, I want to sync the list to the server with HttpClient. How can I observe changes to the array? I tried:

@inject(ObserverLocator)
export class ViewModel {

    constructor(obsLoc) {
        this.list = [];
        obsLoc.getObserver(this, 'list');
            .subscribe(li => console.log(li));
    }
}

But I got neither error nor log message.

like image 299
Matthew James Davis Avatar asked May 17 '15 05:05

Matthew James Davis


1 Answers

getObserver returns a property observer which will notify you when the ViewModel class instance's list property changes. This will only happen when you assign a new value to the list property, ie this.list = [1,2,3]. If you're not assigning new values to the list property and instead are mutating the value of the property via push, pop, splice, etc, you'll want to use an array observer. Use the ObserverLocator's getArrayObserver method- it takes one parameter, the array you want to observe:

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

@inject(ObserverLocator)
export class ViewModel {

    constructor(obsLoc) {
        this.list = [];
        obsLoc.getArrayObserver(this.list);
            .subscribe(splices => console.log(splices));
    }
}

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 {BindingEngine} from 'aurelia-binding'; // or from 'aurelia-framework'

@inject(BindingEngine)
export class ViewModel {
  constructor(bindingEngine) {
    this.list = []; // any Array, Map and soon Set will be supported

    // subscribe
    let subscription = bindingEngine.collectionObserver(this.list)
      .subscribe(splices => console.log(splices));

    // be sure to unsubscribe **later**
    subscription.dispose();
  }
}
like image 97
Jeremy Danyow Avatar answered Oct 08 '22 04:10

Jeremy Danyow