<compose> - How to observe when viewModel.currentViewModel changes?

Is there any way to know when vmInstance.currentViewModel-property of is available? I’m doing dynamic composition like this:

<compose repeat.for="vm of viewModelsArray" view-model.bind="vm" compose.ref="vmRefs[$index]"></compose>

And I have other code needs to access the currentviewModel-property of vmRefs-array. But it takes a while for this to be populated on startup and “viewModelsArray” could change, and then the currentViewModel will also change of course.

Right now I’m using this getter which aurelia polls but I wonder if I can avoid the polling:

 private get instances() {
    if (this.vmRefs) {
      return this.vmRefs.map((ref) => ref.currentViewModel);
    }
  }
1 Like

I think we can have a a composed event for when a composition has been completed. Though there are cases when there are only model changes, not sure what even it would be, or just ignore?

Thanks for your reply @bigopon!

So if I understand you correctly, there’s no way to know when currentViewModel changes in the framework right now? Can I set up an observer in some way or will it result in polling like my current getter “get instances()”?

Yes, some sort of event would be nice to have in the future!

2 Likes

currentViewModel is internal member. It has never been intended to be used outside of the <compose> element itself. It just serves to keep the view model instance of the last successful composition so that if only the view or model changes, it recomposes with the “current” instance of the specified view model.
Adding some kind of composed event was discussed before, somewhere, but it was deferred for vNext.

1 Like

Also if there is only a model change, currently it will just try to reactivate the current view model instance - currentViewModel, it will not trigger a new composition.

1 Like

Thanks! currentViewModel has been useful for us in cases where we know that the view-model will always adhere to an interface or have a base class with a public interface. I can also see that @vheissu has been using it in the step-componenet of a wizard: https://github.com/Vheissu/aurelia-wizard

I did not know about the reactivation when model changes, thanks for that! I have been using other ways to get data into my custom elements (mostly the aurelia-store) since I thought it was a one time thing. Maybe the docs could be improved here?

1 Like