【问题标题】:Backbone Collection Initialization in View视图中的主干集合初始化
【发布时间】:2015-07-11 23:00:44
【问题描述】:

我很难使用从 API 中提取的集合来初始化简单视图。当我尝试从视图中返回集合时,我尝试的所有操作都返回一个空数组。

app.models.Employee = Backbone.Model.extend({

});

app.collections.Employees = Backbone.Collection.extend({

    Model: app.models.Employee,
    url: "http://api.sample.com",

    initialize: function(){
        this.fetch();
    },

    parse: function(response){
        console.log(response)
    },

});

app.views.Container = Backbone.View.extend({
    el: $('.container'), 

    initialize: function(){
        this.collection = new app.collections.Employees();
        console.log(this.collection)
        var that = this;
        this.collection.fetch({
            success: function(){
                that.render();
            }
        });
    },

    render: function(){
        console.log(this.collection) //returns no models
    }
});

【问题讨论】:

  • 所以...看起来您可能通过将 console.log 放入解析中来阻止数据解析?尝试删除完全不必要的覆盖解析方法?
  • 你确实意识到你调用了两次 fetch,对吧?

标签: backbone.js collections backbone-views


【解决方案1】:

你必须正确使用parse

parse: function(response) {
    console.log(response);
    return response;
} //`,` - remove it at last item in object

【讨论】:

    【解决方案2】:

    你的代码有3个问题

    • 您错误地使用了parse。根据规范

    该函数传递原始响应对象,并且应该返回 模型属性数组要添加到集合中

    是的,正如@Sergey 建议的那样

    parse: function(response) {
        console.log(response);
        return response;
    } 
    

    或者更好,只需删除您的 parse 函数,不要覆盖它。

    • 您正在调用您的fetch 函数两次。

    第一次在这一行

    this.collection = new app.collections.Employees();
    

    最终调用这个函数

    initialize: function(){
            this.fetch();
        },
    

    第二次是在视图中的初始化函数中。

    3) 你打破了render

    同样,与您的parse 相同。你应该这样做

    从模型数据渲染视图模板,并更新 this.el 新的 HTML

    像这样的

      render: function() {
        this.$el.html(this.template(this.model.attributes));
        return this;
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-19
      • 1970-01-01
      • 1970-01-01
      • 2012-11-13
      • 1970-01-01
      相关资源
      最近更新 更多