出于某种原因,我无法在Backbone应用程序中多次实例化视图。我给了undefined is not a function
。为什么会这样?
app.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
视图/ 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
因为它第一次工作,所以它不能是语法错误。
答案 0 :(得分:1)
您指的是question
中的start
和start
中的question
。它形成循环依赖。这就是造成这个问题的原因。
来自require.js - circular dependency文档。
如果你定义一个循环依赖(需要b和b需要a),那么在 这种情况下,当调用b的模块函数时,它将得到一个未定义的 a。的价值。