gpt4 book ai didi

ruby-on-rails - Backbone.js + Handlebars 每个

转载 作者:行者123 更新时间:2023-12-04 10:55:02 25 4
gpt4 key购买 nike

我正在尝试转换 Ryan 的 RailsCast on Backbone.js使用 Handlebars 并被困在一个简单的问题上。

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

gem 'backbone-on-rails'
gem 'handlebars_assets'

在我的 index.jst.hbs ,我有以下几点:
{{entries.length}}

<ul>
{{#each entries.models}}
<li>{{name}}</li>
{{/each}}
</ul>

API 调用似乎正在运行,正如您在屏幕截图中的 7 计数中看到的那样。
enter image description here

但是,并未显示每个模型的内容。这是下面的 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",
"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
}
]

最佳答案

您的 @collection大概是 Backbone.Collection . Handlebars 会将其视为某种数组,因此 {{entries.length}}按预期工作,{{#each entries.models}}迭代正确的次数;然而,Handlebars 不知道如何处理 Backbone.Model里面的 s @collection.models .

转换 @collection使用 toJSON 到原始数据, 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 ),并且您的模板不会意外更改您的模型和集合。

关于ruby-on-rails - Backbone.js + Handlebars 每个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11252107/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com