2016-03-24 7 views
1

Ich habe Probleme mit dem Auffüllen einer Ansicht aus einer Backbone.js-Sammlung.Ich kann eine Backbone.js Ansicht nicht ausfüllen

Hier ist meine Ansicht:

<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> 

Hier Schnipsel meines js Code sind:

//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())); 

Dies ist der Fehler, ich bin immer: Reference: LogDate nicht

definiert ist
+0

Der Code, den Sie freigegeben haben, ist unvollständig ... Es wird nur Syntaxfehler werfen ... Bitte richtigen Code in Fragen ... –

Antwort

3

this.journalCollection.toJSON() wird in ein Array von Modellen aufgelöst.

Sie sollten stattdessen tun dies sein:

this.$el.html(this.template({ 
    models: this.journalCollection.toJSON() 
})); 

und dann in der Vorlage:

<script type="text/template" id="item-template"> 
    <% for(var model in models){ %> 
     // All your HTML ... <%- models[model].calories %> ... etc 
    <% } %> 
</script> 

, die alle Modellinformationen auszudrucken wird die Vorlage mit Ihnen definiert.

+0

besser benennen Sie es als Sammlung .... 'Modell in Sammlung' –

+0

es ist richtig Schleifen . Die Werte werden jedoch nicht angezeigt. Ich habe es als <% - model.logdate%> und <% = model.logdate%> ausprobiert. Was mache ich falsch? Vielen Dank! –

+0

Nevermind, ich habe es herausgefunden. <% = models [Modell] .logdate%> –

Verwandte Themen