Search code examples
ember.jsember-data

How to reload route model from controller in Ember?


I am currently struggling with a task that I expected to be quite easy or common: I'd like to initiate a reload of the route model in the controller. As far as I can see, there is no easy way of doing this? Yes, I can access a RouteInfo object by the target property of the controller, but from there I see no way to refresh the model.

A little background about the task I try to solve: I have a route with a model that provides the last object from a collection that has a certain flag not set (e.g. "not indexed" in route /index-object). Now the user works on this object an triggers an action in the controller which set this flag (to "indexed"). So if I reload the route by navigating back and forth the next object is shown. But I want to trigger this reload directly in the action (without reloading the whole page, of course).

My question: Is this possible or is there another/right way of accomplishing what I try to achieve?


Solution

  • I would approach this a bit differently. Unless the memory requirements of the data are very large you could load the entire collection in the route:

    import Route from '@ember/routing/route';
    
    export default Route.extend({
      model() {
        return someFunctionThatFetchesYourData();
      }
    });
    

    Then in your control use a computed property to filter out the item you want:

    import Controller from '@ember/controller';
    import { computed } from '@ember/object';
    
    export default Controller.extend({
      firstObjectWithProperty: computed('[email protected]', function(){
        return this.model.find(obj => obj.notIndexed);
      }),
    });
    

    Then you can just use {{firstObjectWithProperty}} in your template and if the notIndexed flag is changed it will recompute.