【问题标题】:Backbone: view's model is undefined when passing it a modelBackbone:视图的模型在传递模型时未定义
【发布时间】: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

【问题讨论】:

标签: javascript backbone.js


【解决方案1】:

试试下面的。我为你的视图添加了一个初始化方法,并使用了 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').attributes 已定义。
  • _.template(@model.attributes) 将不起作用,因为 @ 在这种情况下不是正确的,@ 将是类,而不是实例。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多