Reloading model when using transitionToRoute approach


#1

Hey,

Assuming i’m currently in route ‘foo’, it sometimes make sense to requesting a model re-load for the same transition, but invoking TransitionToRoute(‘foo’) would not re-load the model due to:

Note that for routes with dynamic segments, this hook is only
executed when entered via the URL. If the route is entered
through a transition (e.g. when using the `linkTo` Handlebars
helper), then a model context is already provided and this hook
is not called. Routes without dynamic segments will always
execute the model hook.

But in situations such as performing some server invocation that changes too many properties in the model, I’d like to reload the model,

Currently I maintain dirty workarounds to achieve that but I’d like to have a better approach,

Does it make sense to extend the transition mechanism to allow model re-load even though the transition context already contains a model? or is there a better approach?

Thanks.


#2

Is it not simpler to simply use model.reload() function to reload the model whenever required?

For transition to different routes where model is provided, I do the following:

setupController: (controller, model) ->
    model.reload()
    controller.set('model', model)

This will load the model twice when entering the route. (Haven’t yet explored how to handle that.) There must be a better solution.


#3

Hey,

I don’t use Ember Data, I need a way to recall the model hook again.


#5

I’m pretty sure that afterModel should do what you need here:

afterModel: (model) ->
  model.reload()

I’m pretty sure that afterModel will run when using transitionToRoute (tested with v1.5.1), and if afterModel it returns a promise, the transition will wait for the promise to fulfill.


#6

I have come back to this topic a few times now trying to find a solution for this stuff. I was using setupController but that changes some of the nice things model gives you like waiting on the page to load.

So my solution from this topic…

    import Ember from 'ember';
    
    var modelHookRun;
    
    export default Ember.Route.extend({
      beforeModel() {
        modelHookRun = false;
      },
      model(params) {
        modelHookRun = true;
        return this.store.findRecord('topic', params.id, {reload: true});
      },
      afterModel(model) {
        if ( ! modelHookRun) {
          return model.reload();
        }
      },
    });

#7

I think model.fetchByID(params.id) does always a reload.


#8

I had a similar problem. The solution was to pass the the id instead the model to transitionTo() to force the model hook to be called always:

transitionTo(‘my-route’, model);

changed to:

transitionTo(‘my-route’, model.get(‘id’));

see http://emberjs.com/api/classes/Ember.Route.html#method_model