7

我正在尝试将 Ryan在 Backbone.js 上的 RailsCast转换为与 Handlebars 一起使用,但遇到了一个简单的问题。

我似乎无法遍历 JSON 数组并显示结果。我在我的 Gemfile 中使用这些宝石

gem 'backbone-on-rails'
gem 'handlebars_assets'

在我的index.jst.hbs中,我有以下内容:

{{entries.length}}

<ul>
    {{#each entries.models}}
        <li>{{name}}</li>
    {{/each}}
</ul>

正如您在屏幕截图中的 7 计数中看到的那样,API 调用似乎正在工作。 在此处输入图像描述

但是,不会显示每个模型的内容。下面是视图 (index.js.coffee) 和 JSON 响应。

 class Raffler.Views.EntriesIndex extends Backbone.View
      template: JST['entries/index']

      initialize: ->
        #triggered when view gets created, listen to 'reset' event, then re-@render, pass 'this' for context binding
        @collection.on('reset', @render, this)

      render: ->
        $(@el).html(@template(entries: @collection))
        this

JSON:

[
{
"created_at":"2012-06-28T18:54:28Z",
"id":1,
"name":"Matz",
"updated_at":"2012-06-28T18:54:28Z",
"winner":null
},
{
"created_at":"2012-06-28T18:54:28Z",
"id":2,
"name":"Yehuda Katz",
"updated_at":"2012-06-28T18:54:28Z",
"winner":null
},
{
"created_at":"2012-06-28T18:54:28Z",
"id":3,
"name":"DHH",
"updated_at":"2012-06-28T18:54:28Z",
"winner":null
},
{
"created_at":"2012-06-28T18:54:28Z",
"id":4,
"name":"Jose Valim",
"updated_at":"2012-06-28T18:54:28Z",
"winner":null
},
{
"created_at":"2012-06-28T18:54:29Z",
"id":5,
"name":"Dr Nic",
"updated_at":"2012-06-28T18:54:29Z",
"winner":null
},
{
"created_at":"2012-06-28T18:54:29Z",
"id":6,
"name":"John Nunemaker",
"updated_at":"2012-06-28T18:54:29Z",
"winner":null
},
{
"created_at":"2012-06-28T18:54:29Z",
"id":7,
"name":"Aaron Patterson",
"updated_at":"2012-06-28T18:54:29Z",
"winner":null
}
]
4

1 回答 1

11

@collection的大概是一个Backbone.Collection. Handlebars 会将其视为某种数组,因此{{entries.length}}可以按预期工作并{{#each entries.models}}迭代正确的次数;但是,Handlebars 不知道如何处理Backbone.Model里面的 s @collection.models

使用将 转换@collection为原始数据toJSON,Handlebars 知道如何处理简单的 JavaScript 数组和对象:

render: ->
    @$el.html(@template(entries: @collection.toJSON()))
    @

然后调整您的模板以查看entries而不是entries.models

<ul>
    {{#each entries}}
        <li>{{name}}</li>
    {{/each}}
</ul>

演示:http: //jsfiddle.net/ambiguous/tKna3/

Backbone 的一般规则是传递model.toJSON()或传递collection.toJSON()给您的模板,这样他们就不必知道 Backbone 方法(例如get),并且您的模板不会意外更改您的模型和集合。

于 2012-06-28T20:47:09.817 回答