每个Backbone.js + Handlebars

时间:2012-06-28 20:09:38

标签: ruby-on-rails ruby-on-rails-3 backbone.js coffeescript handlebars.js

我正在尝试将Ryan的RailsCast on Backbone.js转换为使用Handlebars并且我遇到了一个简单的问题。

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

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

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

{{entries.length}}

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

API调用似乎正常工作,您可以在屏幕截图中的7个数字中看到。 enter image description here

但是,不显示每个模型的内容。这是下面的View(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
}
]

1 个答案:

答案 0 :(得分:11)

您的@collection大概是Backbone.Collection。 Handlebars会将其视为某种数组,以便{{entries.length}}按预期工作,{{#each entries.models}}迭代正确的次数;但是,Handlebars不知道如何处理Backbone.Model内的@collection.models

使用toJSON@collection转换为原始数据,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),以便您的模板不会意外地改变您的模型和集合。