使用Ember Data正确保存hasMany关系的方法

15

我在我的 Ember.js 应用程序中有一些相关模型(使用 Ember 1.0 和 EmberData 1.0 RC2):

App.List = DS.Model.extend({
    listName : DS.attr( ),
    cards : DS.hasMany( 'card', { async : true } )
});

App.Card  = DS.Model.extend({
    description : DS.attr(  ),
    list : DS.belongsTo( 'list' )
});
我使用以下代码保存模型并将它们添加到hasMany的关系中。

I'm using the following code to save models and add them to a hasMany relationship.


createCard : function(){
    var list = this.get( 'model' ),
        card ;

    card = this.store.createRecord( 'card', {
        description : this.get( 'cardDescription' ),
        list : list
    } );

    card.save().then( function(){
        var cards = list.get( 'cards' );

        cards.then( function(){
            cards.pushObject( card );
            list.save();
        } );
    } );

    this.set( 'cardDescription', '' );
}

当保存 hasMany 集合的父级时,我遇到了间歇性问题。有时卡片会正确地添加到列表集合中(列表具有卡片ID数组),有时卡片会被错误地添加(列表具有卡片对象数组),有时关系会完全丢失(列表不包含任何卡片数组)。

这些症状让我认为这是一个异步问题,或者我在保存对象时使用了错误的 promises。

2个回答

3

这看起来与我在这里使用的几乎相同。我唯一能看到的区别是我将子模型推送到父模型中的一个步骤中(我怀疑这没有任何区别),并且在“then”函数内部的承诺主题中有评论(我想你的情况是卡片),也许这会有所不同?

var post = this.get('controllers.post.content');
var comment = this.get('store').createRecord('comment', { post: post, text: this.get('text') });
comment.save().then(function(comment){
  post.get('comments').pushObject(comment);
});

2

对于当前最新的EmberData 1.0.0-beta.4+canary.3993001d,我只在创建模式的didCreate钩子中为每个绑定的关系执行了此操作。目前为止运行良好...

App.Book = DS.Model.extend({
  ...
  didCreate: function() {
    var self = this;
    Em.RSVP.resolve(this.get('author')).then(function(author){
      author.get('books').pushObject(self);
    });
    Em.RSVP.resolve(this.get('category')).then(function(category){
      category.get('books').pushObject(self);
    });
  },
  ...
});

是的,我们正在考虑调查 EPF http://epf.io 作为 Ember Data 的替代方案。这可能会允许更自然的数据同步和关系。 - genkilabs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接