3
我們在Knockout中有一個observableArray,其中包含幾個JSON對象。 在每個JSON對象下,我們有一個需要可觀察的嵌套數組。將嵌套的JSON數據映射到Knockout observableArray
Knockout無法觀察嵌套在每個JSON對象中的數組,在observableArray中。
是否可以映射已嵌套在observableArray中的數組?
以下是observableArray中的一個JSON對象的示例。
注:我們需要使「attributeValues」數組可觀察。
{
"attribute": {
"id": 6,
"name": "Some attribute name",
"typeID": 5
},
"type": {
"id": 5,
"typeName": "list"
},
"attributeValues": [{
"id": 10,
"attributeID": 6,
"value": "Some attribute value",
"chosen": false
}, {
"id": 11,
"attributeID": 6,
"value": "Another attribute value",
"chosen": false
}, {
"id": 12,
"attributeID": 6,
"value": "Third attribute value",
"chosen": false
}]
}
這是我們現在正在使用的代碼:
$.ajax({
type: 'GET',
url: '/JsonService',
success: function (data) {
avm.attributes(data.allAttributes);
},
dataType: 'json',
traditional: true
});
function attributeViewModel() {
var self = this;
self.attributes = ko.observableArray([]);
}
var avm = new attributeViewModel();
ko.applyBindings(avm);
它不工作。在addList()arrayForEach循環後,我把:console.log(self.attributes());並得到:[{},{},{},{},{},{}]。我還驗證了參數'item'中的數據並獲得了正確的數據,但循環之後它不顯示任何數據。 – Gaui
下面的小提琴包含一個工作示例:http://jsfiddle.net/ELMkS/2/。您可以看到數組項目不是空的。 – gbs
這太奇怪了。這裏是我的代碼/輸出:http://pastebin.com/NNYj1bbW - 唯一的區別是你在ko.applyBindings(avm)下面調用avm.addList(),但是在AJAX函數中我稱它爲「成功」。我甚至嘗試將ko.applyBindings(avm)下面的AJAX移動,但沒有運氣。 – Gaui