我有一个名为文档的可观察数组,我从 API 调用的结果中使用 JSON 加载该数组。然后我使用 document 加载当前选定的文档。代码如下:
self.documents = ko.observableArray();
self.document = {
DocID: ko.observable(),
DocName: ko.observable(),
isDocumentEdit: ko.observable(false)
}
function populateDocumentLocations() {
ajaxHelper(url + '/api/Documents/' + self.businessList.busID().busID, 'GET').done(function (data) {
self.documents(data);
});
}
function ajaxHelper(uri, method, data) {
return $.ajax({
type: method,
url: uri,
dataType: 'json',
contentType: 'application/json',
data: data ? JSON.stringify(data) : null
}).fail(function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
});
}
API 返回的两个属性是 DocID 和 DocName。这一切都很好。我向文档添加了第三个字段(如上所述)“isDocumentEdit”,这样我就知道用户是否单击了“编辑”按钮(相应地更改 GUI)。
但是,isDocumentEdit 的值仍为“未定义”而不是 false。
我还尝试循环遍历“documents”并为每个元素添加“isDocumentEdit = false”,但这不起作用。
加载后是否可以向可观察对象添加另一个参数?或者有没有办法在 API 调用时加载它(这是我尝试循环并添加但没有工作的地方)?
最佳答案
当数据从 ajax 调用返回时,需要将其映射到包含可观察值的模型。
首先声明文档 View 模型:
function Document (document) {
var self = this;
self.DocID = ko.observable(document.DocID);
self.DocName = ko.observable(document.DocName);
self.isDocumentEdit = ko.observable(false);
}
然后您可以使用 jQuery $.map 函数将 json 响应映射到您的文档:
function populateDocumentLocations() {
ajaxHelper(url + '/api/Documents/' + self.businessList.busID().busID, 'GET').done(function (data) {
var mappedDocuments = $.map(data, function(document) { return new Document(document) });
self.documents(mappedDocuments);
});
}
这也在 knockout 教程中,这是一个很好的引用:http://learn.knockoutjs.com/#/?tutorial=loadingsaving
关于javascript - 使用 KnockoutJS 从 API 加载字段后,将字段添加到 observableArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27770839/