【问题标题】:backbone collection has empty models after fetch获取后主干集合具有空模型
【发布时间】:2013-06-26 14:42:06
【问题描述】:

我有一个带有嵌入式集合的主干模型,我使用“解析”功能:

var OrderModel = Backbone.Model.extend({
   urlRoot:'/handlers/order',
   defaults:{
      'id':'',
      'name': '',
      'history': new HistoryCollection()
   },
   parse: function(response){
      this.set({'id': response.id});
      this.set({'name': response.name});
      var historyList = new HistoryCollection();
      historyList.add(response.history);
      this.set({history: historyList});
   }
})

收藏

var OrderCollection = Backbone.Collection.extend({
    url: '/handlers/orders/',
    model: OrderModel,
    parse:function(response){
        return response;
    }
});

视图中的代码:

var c = new OrderCollection();
    this.collection.fetch().complete(function(){
    console.log(c);
});

我的服务器返回 JSON,模型未填充。 但是,如果我从 OrderModel 中删除 'parse' 函数,一切正常

【问题讨论】:

    标签: javascript rest backbone.js model


    【解决方案1】:

    Backbone 期望从 parse 函数返回,尝试设置你的模型值而不是只返回你想要的 json,

    parse: function(response){
      var historyList = new HistoryCollection();
      historyList.add(response.history);
      return {
        'id': response.id,
        'name': response.name,
        history: historyList
      };
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多