每个Backbone.js + Handlebars

Dea*_*ean 7 ruby-on-rails coffeescript backbone.js ruby-on-rails-3 handlebars.js

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

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

gem 'backbone-on-rails'
gem 'handlebars_assets'
Run Code Online (Sandbox Code Playgroud)

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

{{entries.length}}

<ul>
    {{#each entries.models}}
        <li>{{name}}</li>
    {{/each}}
</ul>
Run Code Online (Sandbox Code Playgroud)

API调用似乎正常,正如您在屏幕截图中的7个数字中所看到的那样. 在此输入图像描述

但是,不显示每个模型的内容.这是下面的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
Run Code Online (Sandbox Code Playgroud)

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
}
]
Run Code Online (Sandbox Code Playgroud)

mu *_*ort 11

@collection大概是你的Backbone.Collection.把手会将它看作某种数组,因此{{entries.length}}按预期工作并{{#each entries.models}}迭代正确的次数; 但是,Handlebars不知道如何处理Backbone.Model内部的s @collection.models.

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

render: ->
    @$el.html(@template(entries: @collection.toJSON()))
    @
Run Code Online (Sandbox Code Playgroud)

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

<ul>
    {{#each entries}}
        <li>{{name}}</li>
    {{/each}}
</ul>
Run Code Online (Sandbox Code Playgroud)

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

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