我正在尝试将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个数字中看到.
但是,不显示每个模型的内容.这是下面的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","id":3,"name":"DHH","id":4,"name":"Jose Valim",{
- "created_at":"2012-06-28T18:54:29Z","id":5,"name":"Dr Nic","updated_at":"2012-06-28T18:54:29Z","id":6,"name":"John Nunemaker","id":7,"name":"Aaron Patterson","winner":null
- }
- ]
解决方法
你的@collection可能是一个Backbone.Collection. Handlebars会将它看作某种数组,以便{{entries.length}}按预期工作,{{#each entries.models}}迭代正确的次数;但是,Handlebars不知道如何使用@ collection.models中的Backbone.Model.
使用toJSON
将@collection转换为原始数据,Handlebars知道如何处理简单的JavaScript数组和对象:
- render: ->
- @$el.html(@template(entries: @collection.toJSON()))
- @
然后调整模板以查看条目而不是entries.models:
- <ul>
- {{#each entries}}
- <li>{{name}}</li>
- {{/each}}
- </ul>
演示:http://jsfiddle.net/ambiguous/tKna3/
Backbone的一般规则是将model.toJSON()或collection.toJSON()传递给您的模板,这样他们就不必了解Backbone方法(例如get),这样您的模板就不会意外地改变你的模板模特和收藏品.