javascript - 我无法填充 backbone.js View

标签 javascript backbone.js

我在从 backbone.js 集合填充 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>

以下是我的 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: 未定义日志日期

最佳答案

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>

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

关于javascript - 我无法填充 backbone.js View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36209468/

相关文章:

javascript - backbone.stickit 和 html 表单 : How to save (patch) only changed attributes?

coffeescript - 开始使用 Backbone 和 CoffeeScript

javascript - 触发回调绑定(bind)上的 Backbone.js 未按预期工作

javascript - 将主干与第三方 API 一起使用

javascript - 无法将 base64 字符串分配给类属性 - javascript

c# - 如何在允许 HTML 输入的同时防止 XSS(跨站点脚本)

javascript - Backbone.js 按钮单击事件会针对按钮的所有实例触发,而不仅仅是被单击的实例。为什么?

javascript - 刷新时获取json数据

javascript - React Native 中的条件组件

jquery - 主干模型保存上没有方法 'get'