1

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?

https://stackoverflow.com/a/6476507

Nesting Views within Views in backbone js

Community
  • 1
  • 1
j.koch
  • 8
  • 3
  • 8
  • Have you try `class MenuItemsView extends Backbone.View` instead of `class exports.MenuItemsView extends Backbone.View` ? – Atinux Jan 20 '12 at 15:36

1 Answers1

1

Since you're not using MenuItemsView within the class definition of MenuItemView, there shouldn't be any problems. Try changing

childView = new MenuItemsView

To:

childView = new exports.MenuItemsView

It looks like you put the MenuItemsView into the exports namespace, but initialize is looking for a class called MenuItemsView within its own local namespace.

Kevin Peel
  • 4,090
  • 3
  • 23
  • 21