1
votes

I am still a little confused about the way Ember fetches data from remote API and save them in the browser.

So I have created a REST Adapter to get sets of records with an Ajax call, a serializer, and the corresponding model. Suppose they are posts, and I have successfully made a posts index page where the user can click on any post to get into the post detail page.

The Ajax call happens on the index page, and using the Ember inspector, it is clear that all the records are stored in the local store.

But when I click the "back link" which is available on every post detail page, it does redirect to '/posts/' but it seems to make the ajax call again. So all the posts are fetched from the API once again making the page much less responsive.

Here's my questions:

  1. How does that part of Ember work and how do I make Ember simply get the records from the local store without making Ajax call again and again? (unless the user refresh the browser)
  2. If I make a GET request to 'post/1' , no data will be available since in this route no Ajax call should be made. But how do I let the data show? Should I set up another REST adapter for individual post or is it possible to get the record from the local store if an Ajax call has been made?

Hope that makes sense and thanks in advance!

Update:

My post adapter:

App.PostAdapter = DS.RESTAdapter.extend({
    findAll: function(store, type, sinceToken) {
      var url = 'THE URL TO GET JSON BACK'; 
      return $.getJSON(url).then(function(data) {
        return posts;
    })
  }
});

My Post and Posts routes:

App.PostRoute = Ember.Route.extend({
  model: function(params) {
    return this.store.find('post', params.postId);
  }
})

App.PostsRoute = Ember.Route.extend({
  model: function() {
    return this.store.find('post');
  }
})
1

1 Answers

1
votes

Regarding your first question: It depends on the model callback of your route. If you use the all method of the store, the Ajax Request won't be made again. (But: You'd be responsible to get the data the first time around. You way want to sideload it somewhere or may want to call find if all didn't return anything. It depends on your application.

Regarding your second question: The RESTAdapter should be available for single data items as well as for lists. You can implement a model hook in the route using find. If you link-to this route with an object (instead of an ID), this hook won't be called. So the hook would only be called when needed.