Transition from one route to another with a differ

2019-02-26 16:01发布

问题:

I have a search page where we are getting different types of search results. In the list of search results I would like to use

{{#linkTo 'someResources.someResource' result}}{{result.Name}}{{/linkTo}}

And on the route someResources.someResource I want to use a totally different model than on the search page. How do I do that? When I click on the link for the linkTo it doesn't load the model again, instead it tries to use the model named result here.

So what I would like to do is to reload the model when I navigate to someResources.someResource based on the values in result.

The I do have a model named App.SomeResource and a find method for it that works if I go directly to that page.

回答1:

Ember will bypass the model() hook when using linkTo as you've discovered. The assumption is that you passed a model to it, so it and will use that(result) as the model.

The next hook you can use is setupController. Since you have a model hook that works on the direct route, you can use call it directly from here.

One caveat is that you need to also allow for the direct route loading where the model will already have loaded.

setupController: function(controller, model) {
  if (!model.isModel) {
    this.model().then(function(result)) {
      controller.set('model', result)
    }
  }
}

model.isModel is this check via an isModel property on the directly loaded model, which should be absent when passed with linkTo.

Note: the above code assumes that you are returning a Promise in your model() hook.



回答2:

Since the problem is that I want a full reload of the model when doing the transition using linkTo won't work since that is using the model given to it. The solution to the problem is actually quite simple, just use a regular html a-tag instead. What I ended up doing was this:

<a {{bindAttr href="somePropertyInYourModel"}}>{{someTextProperty}}</a>

The property somePropertyInYourModel is a property containing the url to the new page. If the url is in the ember routes it will be as if you where typing that address in the address bar and pressing enter, but without the full reload of the page.

I think this is something that could be improved in ember, it would be much nicer if I could write something like:

{{#linkToRoute "resourceA.routeB" params="val1,val2,val3"}}Go here{{/linkToRoute}}

given I have this routes set up:

App.Router.map(function() {
    this.resource("resourceA", {{path: "/resourceA"}}, function() {
        this.route("routeB", {{path: "/:prop1/:prop2/:prop3");
    }
});

I would like to get:

<a href="#/resourceA/val1/val2/val3">Go here</a>

The order of the val1,val2,val3 matters, if the order is changed they should also be changed in the final url.