ant*_*njs 9 javascript backbone.js backbone-relational
我想使用骨干关系在两个模型User和Task之间建立关系.
两种模型之间的关系如下:
taskModel.creator_id = userModel.id
Run Code Online (Sandbox Code Playgroud)
// TaskModel
var TaskModel = Backbone.RelationalModel.extend({
relations: [
{
type: Backbone.HasOne,
key: 'creator',
keySource: 'creator_id',
relatedModel: Users
}
],
// some code
});
Run Code Online (Sandbox Code Playgroud)
// Task collection
var TaskCollection = Backbone.Collection.extend({
model: TaskModel,
// some code
});
Run Code Online (Sandbox Code Playgroud)
// User Model
var User = Backbone.RelationalModel.extend({
// some code
});
Run Code Online (Sandbox Code Playgroud)
其实问题出在collection.models上,请看附图:
请检查这个jsfiddle:http://jsfiddle.net/2bsE9/5/
var user = new User(),
task = new Task(),
tasks = new Tasks();
task.fetch();
user.fetch();
tasks.fetch();
console.log(user.attributes, task.attributes, tasks.models);
Run Code Online (Sandbox Code Playgroud)

PS:
实际上我使用requireJs来获取UserModel,所以我不能在relatedModel值中包含引号.
define([
'models/user',
'backbone',
'relationalModel'
], function (User) {
"use strict";
var Task = Backbone.RelationalModel.extend({
relations: [
{
type: Backbone.HasOne,
key: 'creator',
keySource: 'creator_id',
relatedModel: User
}
],
});
);
Run Code Online (Sandbox Code Playgroud)
编辑2:
我更新了 jsfiddle 以反映我在下面建议的更改。只要您在任务中调用 toJSON,到达服务器的就是一个 json 对象,其属性设置为用户的creator_id实际属性。id这里keyDestination是多余的,因为文档指出如果您使用 则它会自动设置keySource。
编辑:
https://github.com/PaulUithol/Backbone-relational#keysource
https://github.com/PaulUithol/Backbone-relational#keydestination
https://github.com/PaulUithol/Backbone-relational#includeinjson
以上三者的结合可能会解决您的问题。
var Task = Backbone.RelationalModel.extend({
relations: [
{
type: Backbone.HasOne,
// The User object can be accessed under the property 'creator'
key: 'creator',
// The User object will be fetched using the value supplied under the property 'creator_id'
keySource: 'creator_id',
// The User object will be serialized to the property 'creator_id'
keyDestination: 'creator_id',
// Only the '_id' property of the User object will be serialized
includeInJSON: Backbone.Model.prototype.idAttribute,
relatedModel: User
}
],
});
Run Code Online (Sandbox Code Playgroud)
该文档还指出您的代码指定的属性keySource或keyDestination不应使用该属性。该属性不能作为属性来访问。
请尝试此操作并评论是否可以解决您的问题。
顺便说一句,这是一篇很好的博客文章,它使用了骨干关系端到端。 http://antoviaque.org/docs/tutorials/backbone-relational-tutorial/
| 归档时间: |
|
| 查看次数: |
1750 次 |
| 最近记录: |