7

Ryan의 RailsCast on Backbone.js을 Handlebars와 함께 사용하려고하면 간단한 문제가 발생합니다.Backbone.js + 핸들 바 각

JSON 배열을 반복하고 결과를 표시 할 수없는 것처럼 보입니다. 난 내 index.jst.hbs에서

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

다음 한

내 Gemfile에이 보석을 사용하고 있습니다 :

{{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을 어떻게 처리해야할지 모릅니다.

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

을 그리고 단지 entries 보면보다는 entries.models하는 템플릿을 조정 :

toJSON를 사용하여 @collection에 원시 데이터를 변환은, 핸들 바는 간단한 자바 스크립트의 배열과 객체와 무엇을 알고

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

데모 : http://jsfiddle.net/ambiguous/tKna3/

A Backbone의 일반적인 규칙은 백본 메서드 (예 : get)에 대해 알 필요가 없도록 템플릿을 실수로 모델과 컬렉션을 변경하지 않도록 model.toJSON() 또는 collection.toJSON()을 템플릿에 전달하는 것입니다.

+0

팁 주셔서 감사합니다. 나는 그것이 어떻게 작동하는지 시험해 볼 것이다. – Dean

관련 문제