Javascript 主干:视图';s模型在传递模型时未定义
下面是我的简单主干应用程序的全部内容。当我实例化一个新视图时,我会给它传递一个模型,但是当视图调用模型上的Javascript 主干:视图';s模型在传递模型时未定义,javascript,backbone.js,Javascript,Backbone.js,下面是我的简单主干应用程序的全部内容。当我实例化一个新视图时,我会给它传递一个模型,但是当视图调用模型上的属性时,它会说模型未定义: class App.Recipe extends Backbone.Model class App.RecipeList extends Backbone.Collection url: '/users/4/recipes' model: App.Recipe @recipeList = new App.RecipeList @recipeList.f
属性时,它会说模型未定义:
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]
返回一个JSON对象,该对象确实具有属性
属性。因此,当我实例化视图并向其传递一个模型时,为什么会得到未捕获的TypeError:cannotreadproperty'attributes'of undefined
我猜,@model
在我传入模型之前,会在运行时得到评估。有没有办法推迟?还是我错了
我还尝试了视图的initialize函数中的\uuu.bindAll@
。没有骰子
PS-我显然是一个noob,所以如果你看到其他反模式或我将在这里遇到的东西,请随意提及它们
编辑
我已经尝试过在我的initialize
方法中添加内联模板的答案,如下所示:
class @App.RecipeView extends Backbone.View
tagName: 'li'
initialize: ->
_.bindAll @, 'render'
template = _.template $('#featured_recipes').html()
render: ->
@$el.html @model.toJSON()
@
但随后我得到了无法调用未定义的的方法'replace',我知道这是从对DOM中还没有的东西的下划线调用模板中得到的,这是因为在DOM呈现之前调用了该方法。有什么想法吗
编辑2
现在,我已经将整个应用程序移动到了我的haml
布局的页脚中,这样$(#特色-_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())
@
但我仍然得到无法调用未定义的方法“replace”
请尝试以下操作。我在您的视图中添加了一个initialize方法,并使用Backbone的Collection get方法来获取您的配方
class App.RecipeView extends Backbone.View
initialize: (options) ->
@model = options.recipe
template: _.template(@model.attributes)
render: ->
@$el.html(@template)
@
@view = new App.RecipeView
recipe: recipeList.get(0)
如果我在控制台中使用recipeList.get('c1')
(0是模型数组的索引,但是get
显然需要一个id,因此c1
在那里工作),它会返回一个模型,但我更新了代码以反映您的模型,即使recipeList.get('c1')
确实返回了一个模型,@model.attributes
仍未定义。我还确认了recipeList.get('c1')。属性已定义。\uU9.template(@model.attributes)
将不起作用,因为在该上下文中,@
将是类,而不是实例。可能的副本