7

我試圖將Ryan的RailsCast on Backbone.js轉換成與Handlebars一起工作,並陷入了一個簡單的問題。我不能似乎能夠遍歷JSON數組並顯示結果。我在我的Gemfile使用這些寶石Backbone.js +每把把手

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 [email protected], 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 
} 
] 

回答

11

@collection是,據推測,一個Backbone.Collection。把手將看到它作爲某種排列,因此{{entries.length}}按預期工作,{{#each entries.models}}迭代正確的次數;然而,Handlebars不知道如何處理@collection.models內的Backbone.Model

轉換使用toJSON@collection原始數據,把手知道如何處理簡單的JavaScript數組和對象做:

render: -> 
    @$el.html(@template(entries: @collection.toJSON())) 
    @ 

,然後調整您的模板來看看剛剛entries而非entries.models

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

演示:http://jsfiddle.net/ambiguous/tKna3/

A Backbone的一般規則是將model.toJSON()collection.toJSON()傳遞到您的模板,以便他們不必知道Backbone方法(如get),以便您的模板不會意外更改模型和集合。

+0

感謝您的提示。我會試着看看它是如何工作的。 – Dean