我有一個Backbone應用程序,其中從服務器獲取的JSON並不完全是1對1,我希望我的模型看起來如何。我使用自定義的解析函數爲我的模型,例如:尋找設計模式創建多個模型/集合出單個JSON響應
parse: function(response) {
var content = {};
content.id = response.mediaId;
content.image = response.image.url;
return content;
}
這是有效的。但是,在某些情況下,我有一個API調用,在那裏我得到很多的信息一次,例如,有關使用其user
和comments
圖像:
{
"mediaId": "1",
"image": {
"title": "myImage",
"url": "http://image.com/234.jpg"
},
"user": {
"username": "John"
},
"comments": [
{
"title": "Nice pic!"
},
{
"title": "Great stuff."
}
]
}
我將如何去創造一個新的用戶模型,來自這裏的評論集合?這是一個選項:
parse: function(response) {
var content = {};
content.id = response.mediaId;
content.image = response.image.url;
content.user = new User(response.user);
content.comments = new Comments(response.comments);
return content;
}
這裏的問題是,通過與生JSON創建new User
或new Comments
作爲輸入,骨幹將剛纔添加的JSON屬性的屬性。相反,我想有一個類似中間方法來獲得對物體結構的控制。以下是一個選項:
parse: function(response) {
// ...
content.user = new User({
username: response.user.username
});
// ...
}
...但這不是非常乾燥的證明。
所以,我的問題是:從1個JSON響應中創建多個模型/集合,並控制模型/集合屬性,會是一個不錯的模式?
謝謝!
謝謝!升級到0.9.9打破了我的代碼(還沒有想出如何,但總是運行'parse'可能與它有關:)但你的其他解決方案完全沒問題 – Phortuin