【问题标题】:Backbone.js + Handlebars eachBackbone.js + Handlebars 各
【发布时间】:2012-06-30 09:55:54
【问题描述】:

我正在尝试将 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 的计数。

但是,没有显示每个模型的内容。下面是视图 (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
}
]

【问题讨论】:

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


    【解决方案1】:

    您的@collection 大概是Backbone.Collection。 Handlebars 会将其视为某种数组,因此{{entries.length}} 按预期工作,{{#each entries.models}} 迭代正确的次数;但是,Handlebars 不知道如何处理 @collection.models 中的 Backbone.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),这样您的模板就不会意外改变你的模型和收藏。

    【讨论】:

      猜你喜欢
      • 2013-02-08
      • 2012-07-10
      • 2012-07-23
      • 2015-06-26
      • 2013-10-23
      • 2014-08-12
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      相关资源
      最近更新 更多