我正在尝试将 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
}
]