简体   繁体   中英

Prevent ember-data from reloading relations from server if they are specified as links

I'm using Ember-CLI 0.2.7 with Ember-Data v1.0.0-beta.19.2 and Ember 1.13.0 . I'm facing the following problem:

I have tags which have many items. So there is a hasMany relation from tags to items. An item can also belong to many tags to there is also a hasMany relation into the other direction.

Therefore the file models/tag.js looks as follows:

export default DS.Model.extend({
    //...
    // Relationships
    items: DS.hasMany('item', {async: true}),
    //...
});

and models/item.js

export default DS.Model.extend({
    //...
    // Relationships
    tags: DS.hasMany('tag', {async: true}),
    //...
});

When I request all tags from the server, the server responses with

{
    "meta": {
        "total": 162
    },
    "tags": [
        {
            "id": 1,
            // ...
            "links": {
                "items": "/tags/1/items"
            }
        }
    ]
}

Now if I'm doing somewhere var items = tag.get('items') Ember-Data correctly fetches the items belonging to the tag with an ajax call. But depending from where the user enters a certain page it could be possible that all items are already in the store. So a ajax call is unnecessary. Is there a way to tell Ember-data that the items are already in the store and that it can lookup all items to the tag in the store?

The use case where a subsequent ajax call is annoying for me is a simple version of infinite scroll . Fetching all the items again from the server is not good for the UX because it makes scrolling stuttering. The best thing in my opinion would be to preload all items with a single ajax call and then resolve the relations to the tag with the items in memory.

Is there any chance to achieve this behavior? Some reopen, extend, overwrite etc?

With links there is no way to achieve: if all items already are in the store or not.

You could use ids instead of links :

{
  "tags": [
    {
        "id": 1,
        // ...
        "items": [1, 2, 3],
    }
  ]
}
// or "item_ids" in case of ActiveModelAdapter

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