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?