2013-07-26 43 views
1

虽然使用主干来打api,但我发现我只需要在响应中包含一些数据。除了关于我不需要的对象的数据之外,网络服务器还提供了元数据。如何在backbone.js中进行自定义模型数据解析?

以下解决方案有效,但感觉不对。有没有这样做的标准方式?

var accountsCollection = new AccountsCollection(); 

accountsCollection.fetch({success : function(collection){ 
    var results = new AccountsCollection(); 
    collection.each(function(item){ 
     results.add(new AccountModel({ 
      id: item.toJSON().result[0].id, 
      messageText: item.toJSON().messageText, 
      address1: item.toJSON().result[0].address1, 
      address2: item.toJSON().result[0].address2 
     })); 
    }); 

    onDataHandler(results); 
}}); 

编辑:这是我基于公认的答案最终解决方案:

parse: function(response) { 
     var accounts = []; 
     _.each(response['result'], function (account) { 
      accounts.push(account); 
     }); 
     return accounts; 
    } 
+0

为什么不干脆忽略不需要的数据?更清洁,并且不像您使用上述方式节省任何处理。 – MBHNYC

+0

@MBHNYC它不是更清洁,因为当我打电话保存它会试图坚持这些东西,而且我必须在我的模板中的每个字段之前写入.result [0],并尝试使用我的模型。它混淆了整个应用程序。 – samspot

回答

4

你可以尝试重写Backbone.Collection.parse方法,并做一些疯狂的东西下划线。没有它是否适合你的数据想法..

var keysILike = ['foo', 'bar']; 

AccountsCollection.extend({ 
    parse: function(response) { 
    return _.compact(_.flatten(_.map(response, function (model) { 
     var tmp = {}; 
     _.each(_.keys(model), function (key) { 
     if (_.contains(keysILike, key)) tmp[key] = model[key]; 
     }) 
     return tmp; 
    }))); 
    } 
}); 

对于@舒尚特的迷死你一定要使用此解决方案:

var keysILike = ['foo', 'bar']; 

AccountsCollection.extend({ 
    parse: function(response) { 
    _.each(response, function (model) { 
     _.each(_.keys(model), function (key) { 
     if (!_.contains(keysILike, key)) delete model[key] 
     }) 
    }); 
    return response; 
    } 
}); 
+1

+1 ..这是一个更好的主意,比OP的尝试..哈希方法..也可以避免一个额外的对象来存储所有的链接键..相反,只是从响应对象删除数据..'if(!_ .contains(keysILike,key))删除响应[key];'而且只是回复回复 –

+0

啊这更简单了,谢谢! – cr0

+0

@ cr0 ..不客气。但是这是对已经编写的代码的补充;) –

相关问题