title: How to resolve circular dependencies with nested views in Backbone.js
body: <p>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.</p>
  
  <p>In addition I have a MenuItemView (for individual items) as well as a MenuItemsView (for collections of items). Stripped down, they look like this:</p>
  
  <pre><code>class MenuItemView extends Backbone.View
    tagName: 'li'
  
    initialize: (options) -&gt;
        if @model.get('children')?
            childCollection = new MenuItemList
            childView = new MenuItemsView
                el: $('&lt;ul&gt;').appendTo @el
                collection: childCollection
  
  class exports.MenuItemsView extends Backbone.View
      initialize: (options) =&gt;
          @collection.bind 'add', @add
  
      add: =&gt;
          view = new MenuItemView { model: @collection.last() }
  </code></pre>
  
  <p>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.</p>
  
  <p>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?</p>
  
  <p><a href="https://stackoverflow.com/a/6476507">https://stackoverflow.com/a/6476507</a></p>
  
  <p><a href="https://stackoverflow.com/q/7668760">Nesting Views within Views in backbone js</a></p>