Search code examples
aurelia

Aurelia Observe properties in a dynamic array of objects


I have an array that has some objects inside of it.

this.mediaService.media.files = [
  { id: 1, progress: 15 },
  { id: 2, progress: 0 }
]

As a file is uploaded the progress changes in this external js singleton class that contains .files. I need to subscribe to this array and to the property of progress for each file in the array. This array is dynamic so as files are added I need to be able to know this and subscribe to them.

Here is what I have in aurelia:

  bind() {
    this.observerLocator
      .getArrayObserver(this.mediaApi.media.files)
      .subscribe(this.addSplicesObservations);
  }

  addSplicesObservations(splices) {
    for (let i = 0; i < splices.length; i++) {
      this.subscriptions.push(this.observerLocator
        .getObserver(this.mediaApi.media.files[splices[i].index], 'progress')
        .subscribe(this.onChange)
      );
    }
  }

I noticed though that I don't have access to this inside of addSplicesObservations(). What is the proper way to do this in aurelia?


Solution

  • I learned if you do it this way the this will be preserved.

    bind() {
        this.observerLocator
          .getArrayObserver(this.mediaApi.media.files)
          .subscribe((splices) => {
            this.addSplicesObservations(splices); });
    }
    

    Notice the subscribe setup is a little different. Now why does that make it different I am not sure.