#link-to versus url in browser

How can I ensure that clicking a link-to has the same behavior as entering the same url directly into the browser, which has the side-effect of refreshing the page?

I notice some subtle differences between the two and wonder why.

Which differences have you noticed?

The behavior of route handling and transitioning seems to be different.

There is a documented difference for the link-to helper in providing a model or providing a model’s id. Is that perhaps the difference you’re observing?

If that is the case, the only difference would be that accesing the route through URL you need to find the required model in the route model hook while it is not needed using link-to helper couse you have already provided it.

The best way to see the differences is to open up the devtool console and see the steps yourself, very enlightening.

{{#link-to 'category.post' category post}} - This won’t trigger the model hooks on either the category or post route as you are supplying the models directly.

{{#link-to 'category.post' 1 1}} - This will trigger both model hooks as you are only passing an ID rather than a full model. It’s more or less equivalent to accessing directly via browser’s address bar (although that will also load any additional things that the application route requires).

Does that account for the differences you’re seeing?

3 Likes

Another thing to consider if you are using Ember Data - if you already have the model in the store then store.find('post', 1) will immediately return the cached model. If you would like to retrieve the latest version of the post (as would happen if you accessed via URL) you will need to call .reload() on the post model instance.

Eg.

model: function(params) {
  if (this.store.hasRecordForId(params.post_id)) {
    return this.store.getById(params.post_id).reload();
  } else {
    return this.store.find('post', params.post_id);
  }
}

It’s worth noting that this was a common requirement so Ember Data now has a .fetch method that handles this for you:

model: function(params) {
  this.store.fetch('post', params.post_id);
}
1 Like

Hi kgish, what you’ve observed is correct.

Ember is designed to facilitate the creation of single-page applications. This means that when navigating to a new internal URL, Ember intercepts the navigation and performs the necessary UI updates without refreshing the page.

When you enter the same URL in the browser and hit ENTER, the browser takes over and forces a full page refresh, without giving Ember a chance to intervene. You’ll see the same behavior with all SPA apps regardless of the framework - try Gmail, for example.

Hope that helps.

Yes that helps alot, thanks!