當您使用骨幹關係reverseRelation它創建一個模型及其relatedModel一個雙向關係。如果你看Backbone Relational頁面上的Examples,他們給出了一個通過livesIn鍵在人和房屋之間使用reverseRelation的例子。當你更新關係的任何一方時,它將更新關係的兩邊。
在您的示例中,當您添加帖子是因爲與UserModel和Post有雙向關係時,指定「所有者」將導致現有UserModel(currentUser)也被更新。你會得到的是,當你的用戶帖子也會反映正確的帖子,無論何時你添加一個新的帖子到你認爲我想要的AccountPosts集合。
爲了讓您保留reverseRelation,如果您只想在帖子信息中查看特定的用戶屬性,您可以在includeInJSON屬性中指定這些屬性。
實施例是在此fiddle
// ModelB
var PostModel = Backbone.RelationalModel.extend({
defaults: {
'id': '',
'text': '',
'description': '',
'account': null
}
});
// collection of ModelB
var AccountPosts = Backbone.Collection.extend({
model: PostModel
});
// ModelA
var UserModel = Backbone.RelationalModel.extend({
defaults: {
'id': '',
'customurl': '',
'pictureurl': '',
'emailid': '',
'trackingid': '',
'gender': '',
'mobile': '',
'planid': '',
'posts': null
},
relations: [
{
type: Backbone.HasMany,
key: 'posts',
relatedModel: PostModel,
collectionType: AccountPosts,
reverseRelation : {
key : 'account',
includeInJSON: ['id', 'customurl', 'pictureurl']
}
}
]
});
// json object returned from server request
var accountJSON = {
id: 1, emailid: 22222, trackingid: 3333, gender: 'M',
customurl: 'www.myurl.com', mobile: '222-222-2222',
pictureurl: 'www.mypic.com', planid: 444
};
var currentUser = new UserModel(accountJSON);
// json object from server for posts
var postJSON = {
id: 1, text: 'My First Post', description: 'A Post',
account: { id: 1, customurl: 'www.myurl.com',
pictureurl: 'www.mypic.com'}
};
// example of just one post
var post = new PostModel(postJSON);
這JSON是結果
CURRENT USER JSON
{"id":1,"emailid":22222,"trackingid":3333,"gender":"M","customurl":"www.myurl.com","mobile":"222-222-2222","pictureurl":"www.mypic.com","planid":444,"posts":[{"id":1,"text":"My First Post","description":"A Post","account":{"id":1,"customurl":"www.myurl.com","pictureurl":"www.mypic.com"}}]}
POST JSON
{"id":1,"text":"My First Post","description":"A Post","account":{"id":1,"customurl":"www.myurl.com","pictureurl":"www.mypic.com"}}