2016-03-24 8 views
1

私はbackbone.jsコレクションからのビューの作成に問題があります。ここで私はbackbone.jsビューに値を設定できません

<script type="text/template" id="item-template">    
       <div style="float:left;min-height: 200px;min-width: 50%;"> 
        <div style="float:left;"> 
         <h4>Totals for the day: <%- logdate %></h4> 

         <p><strong>Total Calories:</strong> <span><%- calories %></span></p> 
         <p><strong>Total Protein:</strong> <span><%- protein %></span></p> 
         <p><strong>Total Carbohydrates:</strong> <span><%- carbs %></span></p> 
         <p><strong>Total Fat:</strong> <span><%- fat %></span></p> 
         <p><strong>Total Sugar:</strong> <span><%- sugar %></span></p> 

        </div> 
        <div style="float:right;min-height: 200px;min-width: 50%;"> 

        </div> 
        <div style="width: 100%;clear: both;"> 
         <hr> 
        </div>     
       </div>    
       </script> 

が私のjsのコードの抜粋です: にReferenceError:LOGDATEが定義されていない

//the model and collection 
var LogEntry = Backbone.Model.extend({ 
    defaults: { 
     title: 0, 
     logdate: '', 
     calories: 0, 
     fat: 0, 
     carbs: 0, 
     protein: 0, 
     sugar: 0, 
     content: {} 
    }, 
    initialize: function() { 
     /*if (!this.get("title")) { 
     this.set({"title": this.defaults().title}); 
     }*/ 
    } 
}); 

var FoodJournalCollection = Backbone.Collection.extend({ 
    model: LogEntry, 
    localStorage: new Backbone.LocalStorage("foodjournal") 
}); 

//setting the body, template, collection variables 
el: 'body',  
template: _.template($('#item-template').html()) 
this.journalCollection = new FoodJournalCollection(); 

//I'm trying to retrieve the the collection and populate the view 
this.journalCollection.fetch(); 
this.$el.html(this.template(this.journalCollection.toJSON())); 

これは私が得ているエラーがある。ここ

は、私の見解であります
+0

あなたが共有しているコードは完全ではありません...構文エラーが発生します...質問に適切なコードを投稿してください... –

答えて

3

this.journalCollection.toJSON()は、モデルの配列に変換されます。

あなたは代わりにこれを実行する必要があります。

テンプレートで
this.$el.html(this.template({ 
    models: this.journalCollection.toJSON() 
})); 

、その後を:

あなたが定義されたテンプレートを使用してモデル情報のすべてを出力します
<script type="text/template" id="item-template"> 
    <% for(var model in models){ %> 
     // All your HTML ... <%- models[model].calories %> ... etc 
    <% } %> 
</script> 

+0

コレクションとしてのより良い名前... 'モデルのコレクション' –

+0

正しくループしています。ただし、値は表示されません。私は<% - model.logdate%>と<%= model.logdate%>として試しました。私は間違って何をしていますか?ありがとう! –

+0

心配しないで、私はそれを理解しました。 <%= models [model] .logdate%> –

関連する問題