虽然使用主干来打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;
}
为什么不干脆忽略不需要的数据?更清洁,并且不像您使用上述方式节省任何处理。 – MBHNYC
@MBHNYC它不是更清洁,因为当我打电话保存它会试图坚持这些东西,而且我必须在我的模板中的每个字段之前写入.result [0],并尝试使用我的模型。它混淆了整个应用程序。 – samspot