如何解决 Backbone.js 中嵌套视图的循环依赖
我正在使用 Brunch 和 Backbone.js 构建一个应用程序,其中包含嵌套菜单。我创建了一个 MenuItemModel 和一个 MenuItemsCollection,两者都扩展了它们相应的 Backbone-base-objects。
此外,我还有一个 MenuItemView (用于单个项目)和一个 MenuItemsView (用于项目集合)。剥离下来,它们看起来像这样:
class MenuItemView extends Backbone.View
tagName: 'li'
initialize: (options) ->
if @model.get('children')?
childCollection = new MenuItemList
childView = new MenuItemsView
el: $('<ul>').appendTo @el
collection: childCollection
class exports.MenuItemsView extends Backbone.View
initialize: (options) =>
@collection.bind 'add', @add
add: =>
view = new MenuItemView { model: @collection.last() }
如您所见,两个视图之间存在循环依赖关系,并且并非完全出乎意料的是,“childView = new MenuItemsView”行导致我的 JS 中出现“未捕获的引用错误:MenuItemsView 未定义” -安慰。
我的问题是有没有办法解决这个问题?我可以稍后在代码中通过递归函数创建嵌套菜单,但这看起来并不像我想要的那样整洁和独立。此外,我在 SOF 上发现了以下两个实例,人们建议使用与上面代码完全相同的嵌套视图。我做错了什么?
I'm building an app using Brunch and Backbone.js that is to include nested menus. I have created a MenuItemModel and a MenuItemsCollection, both extending their corresponding Backbone-base-objects.
In addition I have a MenuItemView (for individual items) as well as a MenuItemsView (for collections of items). Stripped down, they look like this:
class MenuItemView extends Backbone.View
tagName: 'li'
initialize: (options) ->
if @model.get('children')?
childCollection = new MenuItemList
childView = new MenuItemsView
el: $('<ul>').appendTo @el
collection: childCollection
class exports.MenuItemsView extends Backbone.View
initialize: (options) =>
@collection.bind 'add', @add
add: =>
view = new MenuItemView { model: @collection.last() }
As you can see, there's a circular dependency between the two views, and not entirely unexpectedly, the line "childView = new MenuItemsView" results in a "Uncaught ReferenceError: MenuItemsView is not defined" in my JS-console.
My question is whether there is any way to resolve this? I can create nested menus through a recursive function later in the code, but this doesn't seem as neat and self-contained as I would like. In addition, I found the following two instances on SOF where people suggest using nested views exactly like in the code above. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您没有在
MenuItemView
的类定义中使用MenuItemsView
,因此应该不会有任何问题。尝试更改为:
看起来您将 MenuItemsView 放入了导出命名空间中,但
initialize
正在其自己的本地命名空间中查找名为MenuItemsView
的类。Since you're not using
MenuItemsView
within the class definition ofMenuItemView
, there shouldn't be any problems. Try changingTo:
It looks like you put the MenuItemsView into the exports namespace, but
initialize
is looking for a class calledMenuItemsView
within its own local namespace.