Hi Guys,
I have just started learning Ember few days back, and now I am stuck in a situation.
I have a User model and Post model, both have their route handler. Going to /users displays users and /posts displays me posts. However when I go back to previous route the app reloads data by hitting api.
For example:
- I go to /users, it fetches user data, which is fine,
- When I go to /posts, it fetches post data, fine too,
- Now when I go back to /users it fetch user data again. Means every-time I go to /users or /posts, it fetches data from server. Is it possible to fetch data for the first time only.
App.UsersRoute = Ember.Route.extend({
model: function() {
return this.store.find('user');
}
});
App.PostsRoute = Ember.Route.extend({
model: function() {
return this.store.find('post');
}
});
1 Like
The idea behind that behavior is that if there were any change in /posts
while you where in the /user
page you find new posts by hitting the API and keep the application up to date.
If you want to avoid hitting the API at any time, you can work with local data in routes with store.all('post')
but then you need to set up some mechanism to retrieve new posts, maybe a setInterval
function, or a refresh button somewhere…
Since the controller would still have the users or posts from the previous state, you can always do something like:
model: function() {
// if the controller has content already, just return that
if(this.controller && this.controller.get('content')) {
return this.controller.get('content');
}
return this.store.find('user');
}
3 Likes
Thanks, it worked just fine.
Just to follow up, there are better ways of handling this now. ember-data has facilities in place of loading what is already in the ember-data store without fetching new records from the API.
Force Ember Data to reload data from backend API - Ember Igniter covers the hooks