Array subscription in Aurelia

后端 未结 1 749
感动是毒
感动是毒 2020-12-24 15:18

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 observ

相关标签:
1条回答
  • 2020-12-24 15:50

    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();
      }
    }
    
    0 讨论(0)
提交回复
热议问题