4

It came as a surprise when starting out with Aurelia that if.bind doesn't result in a child view/viewModel getting destroyed. It does go through a bind/unbind attached/detached cycle, and I can see how this makes sense for some scenarios. But I would also like the ability to completely destroy the view/viewModel and recreate it from scratch. I've created a plunker that demonstrates my best effort using if.bind. I'm looking for suggestions on how to have the <my-other-element> completely destroyed. Thanks!

1 Answers1

1

Looks like you can use the <compose> element to treat the custom element as a view/view model and therefore use transient creation behavior. See compose documentation

plunker: https://plnkr.co/edit/vKsQsHKsIp4vTVjG5G7f?p=preview

<template if.bind="someBoolean">
  <compose view-model="my-other-element.js"></compose>
</template>
Joseph Gabriel
  • 8,339
  • 3
  • 39
  • 53
  • This is nicer than my first hack of using `repeat.for`. I would still consider this a hack since I believe compose is intended for situations where one might use different kinds of viewModels. Also Jeremy Danyow [recommends](https://www.danyow.net/aurelia-custom-element-vs-compose/) using Custom Elements over Compose whereever possible. Also of note is that `@transient` doesn't make a difference in this situation, the view/viewModel is treated as transient regardless. Maybe this situation warrants a github issue? – FunkyCodeMonkey Sep 14 '16 at 14:37
  • Correct - I just didn't clean up the transient decorator, but it doesn't really apply here. In this situation, transient is the default behavior. You can use `@singleton()` to instruct the router to reuse the instance. – Joseph Gabriel Sep 14 '16 at 15:10
  • I'm pretty sure that there's no way for a custom element to use a singleton view model. So multiple elements would have each their own view model that gets constructed. But this case is a little different - it seems that the templating engine is hanging onto the element reference and adding it back as opposed to creating it from scratch. A github issue might spur some conversation about this behavior. – Joseph Gabriel Sep 14 '16 at 15:18
  • You're right. Compose is basically the only way to accompish this right now. https://github.com/aurelia/framework/issues/602 Thanks for taking the time to look into it! – FunkyCodeMonkey Sep 15 '16 at 00:48