简体   繁体   中英

Fine-tune refreshing of multiple models in Ember route

There's a well known approach to support loading more than one model promise in an Ember route, using Ember.RSVP.hash :

// app/routes/posts.js

export default Ember.Route.extend({

  model(params) {
    return Ember.RSVP.hash({
      posts: this.store.findAll('post', params),
      tags: this.store.findAll('tag', params),
    });
  },

});

Now I have a page param, to be able to load the posts in batches, instead of loading them and showing them all at once. But page changes do not alter the tags. However, when the page param changes, the whole model of the route is triggered again to re-load, causing the app to re-fetch both the posts for the new page, and the same tags all over again.

Is there a way to fine-tune this so that the tags are not loaded when certain params change?

There are several ways to refacto your code. Like moving tags out of model. Or doing pagination differently (w/o model refresh). The one I like is writing a custom getAll utility.

var cache = {}; // model_name => Promise<[Record]>

function getAll(store, model) {
    if(!store.modelFor(model).cacheable) {
        return store.findAll(model);
    }

    if(!cache[model]) {
        cache[model] = store.findAll(model);
    }

    return cache[model];
}

And in your model now

import { getAll } from 'utils/store';
...
tags: getAll('tag'),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM