我有一个从ajax请求回来的数组。我将此数组绑定到knockout中的observableArray。我想知道如何迭代数组prefixeData
并使每个元素的属性都可观察。这可能吗?
var viewModel = {
name: "Editor",
prefixeData: ko.observableArray([]),
getPrefixes: function (prefix) {
var params = {
"prefix": prefix
};
$.ajax({
type: "POST",
url: "XXXX.aspx/GetPrefixes",
data: JSON.stringify(params),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
var trans = data.d;
if (trans.Successful) {
viewModel.prefixeData(trans.ResultObject);
// this doesnt work
viewModel.prefixeData().forEach(function(data) {
data.LevelName=ko.observable(data.LevelName);
});
} else {
//todo
}
},
error: function (xhr, textStatus, err) {
alert("Status: " + textStatus); alert("Error: " + err);
}
});
}
};
答案 0 :(得分:1)
你需要导入knockout.mapping knockout.mapping
并编辑您的代码,如:
success: function (data) {
var trans = data.d;
if (trans.Successful) {
var observableArray = ko.mapping.fromJS(trans.ResultObject);
viewModel.prefixeData(observableArray());
//viewModel.prefixeData now is observableArray, you can call foreach : viewModel.prefixeData at html
} else {
//todo
}
},