0

出于某种原因,我不能在我的 Backbone 应用程序中多次实例化视图。我被给了undefined is not a function。为什么会这样?

应用程序.coffee

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

  initialize = ->   

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

  initialize: initialize

意见/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

意见/问题.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

由于它是第一次工作,它不可能是语法错误。

4

1 回答 1

1

您指的是questioninstartstartin question。它形成循环依赖。这就是这个问题的原因。

来自require.js - 循环依赖文档。

如果你定义了一个循环依赖(a 需要 b,b 需要 a),那么在这种情况下,当 b 的模块函数被调用时,它会得到 a 的未定义值。

于 2013-10-11T02:36:06.163 回答