0
我想從表示2d數組的JSON字符串中綁定KnockoutJS視圖模型。但是,我只遇到數組第一級顯示的問題。將嵌套的JSON綁定到Knockout視圖模型
我的模型看起來是這樣的:
function CategoriesModel(categories) {
var self = this;
self.categories = ko.observableArray(ko.utils.arrayMap(categories, function (category) {
return {
description: category.description,
checks: ko.observableArray(category.checks)
};
}));
self.addCategory = function() {
self.categories.push({
description: "",
checks: ko.observableArray()
});
};
self.removeCategory = function (category) {
self.categories.remove(category);
};
self.addCheck = function (category) {
category.checks.push({
description: "",
keypoint: "",
penaltypoints: ""
});
};
self.removeCheck = function (check) {
$.each(self.categories(), function() {
this.checks.remove(check)
});
};
self.save = function() {
self.lastSavedJson(JSON.stringify(ko.toJS(self.categories), null, 2));
};
self.lastSavedJson = ko.observable("");
};
在那裏我試圖綁定JSON數據的方法是:
function loadData() {
var rawJSON = '[
{
"description":"01",
"checks":{"
description":"01",
"keypoint":"01",
"penaltypoints":"01"
}
},{
"description":"02",
"checks":{
"description":"02",
"keypoint":"02",
"penaltypoints":"02"
}
}
]';
var parsedJSON = JSON.parse(rawJSON);
viewModel.categories = ko.mapping.fromJSON(rawJSON);
ko.applyBindings(viewModel);
}
誰能告訴我我的錯誤是什麼?任何幫助將不勝感激。
編輯: 我試圖創建一個jsfiddle(http://jsfiddle.net/EAu2E/4/),但似乎knockout.js和knockout-mapping.js資源沒有正確加載。
我已經更新您的提琴,請期待在更新的地址http://jsfiddle.net/EAu2E/7/ – Gabe
爲什麼從JSON映射,當你可以直接從JS對象映射? – haim770
@加貝謝謝你! –