Search code examples
javascriptbackbone.js

I can't populate a backbone.js view


I'm running into problems with populating a view from a backbone.js collection.

Here is my view:

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

Here are snippets of my js code:

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

This is the error that I'm getting: ReferenceError: logdate is not defined


Solution

  • this.journalCollection.toJSON() resolves to an array of models.

    You should be doing this instead:

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

    and then in your template:

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

    which will print out all of the model information using the template you defined.