我可以't填充backbone.js视图

I can't populate a backbone.js view

本文关键字:backbone js 视图 填充 我可以      更新时间:2023-09-26

我在从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未定义

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>

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