主干、RequireJS 和树
我正在将类别树视图重写为 RequireJS 和 Backbone 应用程序。
结构很简单:每个类别都包含子类别的集合。
然而,循环依赖问题很快就会变得明显。类别模型需要类别集合,类别集合需要类别模型。
RequireJS 文档中有关于循环依赖的快速简介:
http://requirejs.org/docs/api .html#circular
但是,我似乎遗漏了一些东西,因为我仍然收到未定义和/或错误。我认为在示例中只看到“b”而不是“a”会让我无法理解。
有谁能够提供一个可以澄清的简单示例吗?那,或者是一种更好的结构方式,不需要循环依赖。
I'm rewriting a category tree view into a RequireJS and Backbone app.
The structure is simple: each category contains a collection of child categories.
However, the circular dependency problem becomes quickly apparent. The category model requires the category collection and the category collection requires the category model.
There is quick blurb about circular dependency in the RequireJS docs:
http://requirejs.org/docs/api.html#circular
However, it seems that I'm missing something because I'm still getting undefineds and/or errors. I think just seeing 'b' and not 'a' in the examples is keeping me from understanding.
Is anyone able to provide a simple example that might clarify? That, or a better way of structuring this that wouldn't require a circular dependency.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于循环引用,当 require.js 加载“b”作为“a”的先决条件时,它无法返回“a”的值,因为 a 的
initModule()
尚未被调用然而。但是,当调用b.somethingElse()
时,模块“a”已初始化,并且require("a")
调用将返回。以下代码显示了两个模块内的内容 - 它们的加载顺序并不重要。我对 require.js 示例进行了一些更改,以使其更加明显。
顺便说一句,虽然一般来说循环引用是糟糕设计的症状,但情况并非总是如此。例如,我实现了一个小部件工厂模块,除其他外,该模块引用了“容器小部件”模块,然后该模块必须引用工厂才能创建其内容。完全合法。
Due to the circular reference, when require.js is loading "b" as a prerequisite for "a", it can't return a value for "a" because a's
initModule()
has not been call yet. However, by the timeb.somethingElse()
is called, module "a" has been initialized and therequire("a")
call will return.The following code shows what's inside both modules - the order in which they get loaded does not matter. I've changed it from the require.js example a little to make it more obvious.
BTW, while in general circular references are a symptom of bad design, that's not always so. For example, I've implemented a widget factory module which, among other things, referenced a "container widget" module which then had to reference the factory in order to create its content. Perfectly legit.