给出以下RelationalModel模型:
var Server = Backbone.RelationalModel.extend({
relations: [{
type: Backbone.HasMany,
key: 'databases',
relatedModel: 'Database',
collectionType: 'DatabaseCollection',
includeInJSON: 'id'
}],
defaults: {
databases: []
},
});
var Database = Backbone.RelationalModel.extend({});
var DatabaseCollection = Backbone.Collection.extend({
model: Database
});
这些对象:
new Database({
id: 1,
name: 'DB1'
});
new Database({
id: 2,
name: 'DB2'
});
var s1 = new Server({
id: 3,
name: 'S1',
databases: [1,2]
});
将此模型序列化/反序列化为接受此JSON结构的最简单/推荐的方法是什么?:
{
databases: [
{ id: 1, name: 'DB1' }
{ id: 2, name: 'DB2' }
],
servers: [
{ id: 3, name: 'S1', databases: [1, 2] }
]
}
这样就可以在一次请求中将数据发送到服务器或从服务器读取数据。
谢谢!
添
答案 0 :(得分:1)
我能够使用您的示例生成您所描述的JSON,并在我刚刚创建的这个小提琴中进行了一些小的更改Example。
由于调试器中显示的一些警告并获得您描述的结果,我进行了这些更改。希望这可以帮助。
这是你最终得到的代码,我刚刚创建了一个简单的旧Backbone模型,将两个集合合并为一个。调用toJSON为您提供了传输到服务器的单个JSON对象。
var Database = Backbone.RelationalModel.extend({});
var DatabaseCollection = Backbone.Collection.extend({
model: Database
});
var Server = Backbone.RelationalModel.extend({
relations: [{
type: Backbone.HasMany,
key: 'databases',
relatedModel: Database,
collectionType: DatabaseCollection,
includeInJSON: 'id'
}],
defaults: {
databases: []
}
});
var ServerCollection = Backbone.Collection.extend({
model: Server
});
var allDatabases = new DatabaseCollection();
allDatabases.add([
new Database({ id: 1, name: 'DB1' }),
new Database({ id: 2, name: 'DB2' }),
new Database({ id: 3, name: 'DB3' }),
new Database({ id: 4, name: 'DB4' })
]);
var allServers = new ServerCollection();
allServers.add([
new Server({
id: 30,
name: 'S1',
databases: [
allDatabases.get(1),
allDatabases.get(2)
]
}),
new Server({
id: 40,
name: 'S2',
databases: [
allDatabases.get(3),
allDatabases.get(4)
]
})
]);
// combine into an object to transfer to server as one
var serverObject = new Backbone.Model({
'servers': allServers,
'databases': allDatabases
});
console.log(serverObject.toJSON());