使用backboneJS + Backbone-relational + requireJS 创建嵌套模型 [英] Creating nested models with backboneJS + backbone-relational + requireJS
问题描述
我是 BackboneJS 的新手,并且使用带有 RequireJS 的 Backbone-relational Model 陷入嵌套关系 - 我想我遇到了循环问题.任何帮助将不胜感激!
I am new to BackboneJS and I am stuck with nested relations using Backbone-relational Model with RequireJS -I think I runned into circular issues. Any help will be highly appreciated!
我有以下模型和系列:
/* Module Model at models/module*/
define([
'jquery',
'underscore',
'backbone',
'backboneRelational',
], function($, _, Backbone) {
var ModuleModel = Backbone.RelationalModel.extend({
urlRoot: 'api/module',
_radius: 50,
relations: [{
type: Backbone.HasMany,
key: 'children',
relatedModel: 'ModuleModel',
collectionType: 'ModuleCollection',
reverseRelation: {
key: 'parent_id',
includeInJSON: 'id'
}
}],
url: function() {
return this.id? 'api/module/' + this.id : 'api/module';
}
});
return ModuleModel;
});
/* Module Collection */
define([
'jquery',
'underscore',
'backbone',
'models/module'
], function($, _, Backbone, ModuleModel) {
var ModuleCollection = Backbone.Collection.extend({
model: ModuleModel,
url: 'api/modules'
});
return ModuleCollection;
});
当我初始化对象ModuleModel时,它抛出以下错误:
When I initialize the object ModuleModel, it throws the following error:
Relation=child; no model, key or relatedModel (function (){ parent.apply(this, arguments); }, "children", undefined)
你能指出我正确的方向吗?
Could you point me to the right direction?
推荐答案
这看起来像是一个范围界定问题.在 ModuleModel
的初始化过程中,它想与自己创建一个 hasMany
关系,但它找不到自己,它会以上述错误的形式给你带来悲伤:
This looks like a scoping issue. During initialization of ModuleModel
it wants to create a hasMany
relation with itself, but it can't find itself and it will give you grief in form of said error:
一旦对象可以从当前作用域到达,事情就开始解决了:
Once the object is reachable from the current scope things start to work out:
一个可能的解决方案是为模型和集合提供一个可以从当前范围访问的命名空间.
A possible solution would be to give models and collection a namespace for themselves which can be reached from the current scope.
希望这会有所帮助.
这篇关于使用backboneJS + Backbone-relational + requireJS 创建嵌套模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!