Backbone/RequireJS 嵌套列表中的循环依赖 [英] Circular Dependency in Backbone / RequireJS Nested List
问题描述
我正在使用 RequireJS 在 Backbone 中设置嵌套类别结构.
I'm setting up a nested categories structure in Backbone with RequireJS.
在这种结构中,一个类别集合包含类别模型,单个类别模型可以包含一个类别集合.
In this structure, a categories collection contains category models, and a single category model can contain a categories collection.
不幸的是,这似乎导致了 RequireJS 中可怕的循环依赖问题.我已阅读 RequireJS 上的文档(http://requirejs.org/docs/api.html#circular)但是我发现'a'和'b'的解释令人困惑.
Unfortunately this seems to cause the dreaded circular dependencies problem in RequireJS. I have read the docs on RequireJS (http://requirejs.org/docs/api.html#circular) however I am finding the explanation with 'a' and 'b' confusing.
这是我的代码,它导致了问题:
Here is my code, which is causing the problem:
define([
"jquery",
"underscore",
"backbone",
"collections/categories"
], function( $, _, Backbone, CategoriesCollection ) {
var Category = Backbone.Model.extend({
defaults: {
title: "Untitled"
},
parse: function(data) {
this.children = new CategoriesCollection( data.children, {parse: true} );
return _.omit( data, "children" );
}
});
return Category;
});
...
define([
"jquery",
"underscore",
"backbone",
"models/category"
], function( $, _, Backbone, CategoryModel ) {
var Categories = Backbone.Collection.extend({
model: CategoryModel
});
return Categories;
});
我想知道是否有人以前经历过这种情况,可以帮助我朝着正确的方向前进.
I am wondering if anyone who has experienced this before can help steer me in the right direction.
(提前)感谢您的帮助,
Thanks (in advance) for your help,
推荐答案
您只需要在模型中需要集合时再次使用 require
集合,因为最初传递的集合可以是未定义的:
You just need to use require
the collection again when you need it in the model, as the Collection passing initially can be undefined:
define([
"jquery",
"underscore",
"backbone",
"collections/categories"
], function( $, _, Backbone, CategoriesCollection ) {
var Category = Backbone.Model.extend({
defaults: {
title: "Untitled"
},
parse: function(data) {
if(!CategoriesCollection){
CategoriesCollection = require("collections/categories");
}
this.children = new CategoriesCollection( data.children, {parse: true} );
return _.omit( data, "children" );
}
});
return Category;
});
在示例中,它们也导入 require
但它也应该在没有导入的情况下工作.
In the example they import also require
but it should also work without the import.
这篇关于Backbone/RequireJS 嵌套列表中的循环依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!