Jezen Thomas
Jezen Thomas

Reputation: 13800

Can’t instantiate Backbone view a second time

For some reason, I can’t instantiate a view more than once in my Backbone app. I’m given undefined is not a function. Why would that be?

app.coffee

define [
  'views/start'
], (
  StartView
) ->

  initialize = ->   

    # Take us to the start view
    startView = new StartView()
    startView.render() # Works just fine

  initialize: initialize

views/start.coffee

define [
  'jquery'
  'underscore'
  'backbone'
  'text!templates/start.html'
  'views/question'
], (
  $
  _
  Backbone
  StartTemplate
  QuestionView
) ->

  StartView = Backbone.View.extend

    events:
      'click #btn-begin': 'pushQuestionView'

    render: ->

      # Create a template and stuff it into the view element
      @$el.html @template = _.template StartTemplate

      # Inject the HTML in the document
      $('#main').html @el

      # Return view for chaining
      @

    pushQuestionView: ->

      questionView = new QuestionView()
      questionView.render()

  StartView

views/question.coffee

define [
  'jquery'
  'underscore'
  'backbone'
  'text!templates/question.html'
  'views/form'
  'views/start'
], (
  $
  _
  Backbone
  QuestionTemplate
  FormView
  StartView
) ->

  QuestionView = Backbone.View.extend

    events:
      'click #btn-prev': 'goBack'

    render: ->

      # Create a template and stuff it into the view element
      @$el.html @template = _.template QuestionTemplate

      # Inject the HTML in the document
      $('#main').html @$el

      # Return for chaining
      @

    goBack: ->

      console.log StartView # => undefined

      startView = new StartView() # => Uncaught TypeError: undefined is not a function
      startView.render()

  QuestionView

Since it worked the first time, it can’t be a syntax error.

Upvotes: 0

Views: 217

Answers (1)

Sathya
Sathya

Reputation: 5308

You are referring question in start and start in question. It forms circular dependency. That is the cause for this problem.

From require.js - circular dependency documentation.

If you define a circular dependency (a needs b and b needs a), then in this case when b's module function is called, it will get an undefined value for a.

Upvotes: 1

Related Questions