我有简单的嵌套JSON:
{
"user": {
"name": "John",
"related": {
"name": "Alice",
"related": {
"name": "Bob"
}
}
}
}
我有Backbone Relational模型“User”:
(function(){
var User = Backbone.RelationalModel.extend({
defaults: {
name: "",
related: {}
},
// Linking this model to itself
relations: [{
type: Backbone.HasOne,
key: "related",
relatedModel: User // As I've expected it doesn't exist at this time
}]
})
})()
所以,问题是:如何将模型与自身联系起来?谢谢!
答案 0 :(得分:1)
Backbone.Relational"相关"模型需要在可访问的范围内,并且在早期版本的Backbone-Rel中,它通常期望模型可以在全局范围内访问。
但是,如果你正在使用Require.js,或者将模型定义包装在一个闭包中,那么它们就不会在这个全局范围内。
此pull request处理此情况。使用最新的Backbone-Rel HEAD,您可以为Backbone-Rel添加自定义范围,以便在以下位置查找相关模型:
(function(){
var models = {};
Backbone.Relational.store.addModelScope(models);
models.User = Backbone.RelationalModel.extend({
defaults: {
name: ""
},
// Linking this model to itself
relations: [{
type: Backbone.HasOne,
key: "related",
relatedModel: 'User'
}]
});
var u1 = new models.User({
name: "John",
related: {
name: "Alice",
related: {
name: "Bob"
}
}
});
console.log(u1.toJSON());
})();
直播jsFiddle示例:http://jsfiddle.net/edwardmsmith/BRmQF/16/