我在我的 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。