Clean up nested resources in a controller when transition back to top level items


I have a sidebar controller, which displays a nested hierarchy of navigation elements. So, for instance, I have a library, when selected it additionally displays all the books within the library. When a book is selected it additionally displays all the pages…

If someone selects a page and then selects the parent library again, I need to clean out all the previously selected children (as they are no longer selected). So, the setupController hook requires the model to be passed, which I don’t have at that point. Granted, I could put it together programmatically, but that’s quite some hassle.

Here is a js bin from a related question, which shows the problem: Select lib1, book1, page1. Then go back to lib1. page1 is still available even though it should have been removed as book1 no longer is selected.

So, I have ended up with doing something like this in the actions hook of my route (code is not directly related to the jsbin, but shows the concept):

willTransition: function(transition) {
      // if we transition back to this route, clean up the previous songs and versions in the sidebar
      if (transition.targetName === 'library.index') {
        var sidebarController = this.controllerFor('sidebar');
        sidebarController.set('books', null);
        sidebarController.set('pages', null);

I need to check if the transition target is back to this route, otherwise this would clean out selected elements when traversing the children. So far this works quite well, but seems like an ugly hack. Is there any better way to do this?