加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 每个Backbone.js把手

发布时间:2020-12-17 04:16:16 所属栏目:百科 来源:网络整理
导读:我正在尝试将Ryan的 RailsCast on Backbone.js转换为使用Handlebars并且我遇到了一个简单的问题. 我似乎无法遍历JSON数组并显示结果.我在我的Gemfile中使用这些宝石 gem 'backbone-on-rails'gem 'handlebars_assets' 在我的index.jst.hbs中,我有以下内容: {
我正在尝试将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),这样您的模板就不会意外地改变你的模板模特和收藏品.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读