我无法填充backbone.js视图

时间:2016-03-24 20:29:37

标签: javascript 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代码的片段:

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

这是我得到的错误: ReferenceError:未定义logdate

1 个答案:

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

将使用您定义的模板打印出所有模型信息。