【发布时间】:2014-03-01 18:01:24
【问题描述】:
这是我的简单 Backbone 应用程序的全部内容。当我实例化一个新视图时,我向它传递了一个模型,但是当视图在模型上调用 attributes 时,它说模型未定义:
class App.Recipe extends Backbone.Model
class App.RecipeList extends Backbone.Collection
url: '/users/4/recipes'
model: App.Recipe
@recipeList = new App.RecipeList
@recipeList.fetch()
class App.RecipeView extends Backbone.View
template: _.template(@model.attributes)
render: ->
@$el.html(@template)
@
@recipeView = new App.RecipeView(model: recipeList.models[0])
$ ->
$('#featured_recipes').html(window.recipeView.render())
在控制台中,recipeList.models[0] 返回一个确实具有 attributes 属性的 JSON 对象。那么当我实例化视图并将其传递给模型时,为什么会得到Uncaught TypeError: Cannot read property 'attributes' of undefined?
我的猜测是 @model 在我传入模型之前在运行时进行评估。有没有办法推迟呢?还是我错了?
我也在视图的初始化函数中尝试了_.bindAll @。没有骰子。
PS — 我显然是个菜鸟,所以如果你看到其他反模式或我将在这里遇到的事情,请随时提及。
编辑
我已经尝试了here 在我的initialize 方法中添加内联模板的答案,如下所示:
class @App.RecipeView extends Backbone.View
tagName: 'li'
initialize: ->
_.bindAll @, 'render'
template = _.template $('#featured_recipes').html()
render: ->
@$el.html @model.toJSON()
@
但后来我得到了Cannot call method 'replace' of undefined ,我知道这是从下划线调用模板对尚未在 DOM 中的东西进行的,这是因为它在我的 DOM 渲染之前被调用。有什么想法吗?
编辑 2
现在我已将整个应用程序移动到我的 haml 布局的页脚中,以便 $(#featured-_recipes') div 位于 DOM 中。然后我将视图更改为:
class @App.RecipeView extends Backbone.View
tagName: 'li'
initialize: ->
_.bindAll @, 'render'
@template: _.template $('#featured_recipes').html()
render: ->
@$el.html @template(@model.toJSON())
@
但我仍然收到Cannot call method 'replace' of undefined 。
【问题讨论】: