How to reload an async with links hasMany relationship?

前端 未结 6 1270
有刺的猬
有刺的猬 2021-01-02 01:34

Lets say we have

Post = DS.Model.extend({
  comments: DS.hasMany({async: true})
})

Comment = DS.Model.extend({
  post: DS.belongsTo()
})

a

6条回答
  •  甜味超标
    2021-01-02 01:56

    With ember-data-1.0.0-beta.10 I'm using the following model extension.

    Just call model.reloadRelationship(name) where name is the name of the model attribute representing the relationship.

    This works for both normal and link belongsTo/hasMany relationships.

    DS.Model.reopen({
        reloadRelationship: function(name) {
            var meta = this.constructor.metaForProperty(name),
                link = this._data.links ? this._data.links[meta.key] : null;
            if (!link) {
                if (meta.kind === 'belongsTo') {
                    this.get(name).then(function(model) { model.reload(); });
                } else {
                    this.get(name).invoke('reload');
                }
            } else {
                meta.type = this.constructor.typeForRelationship(name);
                if (meta.kind === 'belongsTo') {
                    this.store.findBelongsTo(this, link, meta);
                } else {
                    this.store.findHasMany(this, link, meta);
                }
            }
        }
    });
    

    The only thing missing here are some checks, for example a check if the model is already reloading when the model is reloaded with a link or a check to see if the property name exists within the current model.

    EDIT ember-data-1.0.0-beta.14:

    DS.Model.reopen({
        reloadRelationship: function(key) {
            var record = this._relationships[key];
            if (record.relationshipMeta.kind === 'belongsTo') {
                return this.reloadBelongsTo(key);
            } else {
                return this.reloadHasMany(key);
            }
        },
        reloadHasMany: function(key) {
            var record = this._relationships[key];
            return record.reload();
        },
        reloadBelongsTo: function(key) {
            var record = this._relationships[key];
            if (record.link) {
                return record.fetchLink();
            } else {
                record = this.store.getById(record.relationshipMeta.type, this._data[key]);
                return record.get('isEmpty') ? this.get(key) : record.reload();
            }
        }
    });
    

    HasMany relationship will fallback to native reload method.

    For BelongsTo relationship, it will first check if record needs to be reloaded (if it is not loaded before yet, it will only call get to retrieve the record, otherwise it will call reload).

提交回复
热议问题