我试图在knockoutjs中为我的ObservableArray添加一个布尔值,以检查我是否编辑了我的对象。目标是当我单击全部保存时,只有已修改的数据才会发送到后端进行更新。如果值为false,则跳过该对象,如果该对象为true,则将其发送以进行更新。
我尝试用来初始化此代码的代码:
var self = this;
//S1:Boolean to check wheather the operation is for Edit and New Record
var IsNewRecord = false;
self.WorkOrders = ko.observableArray([]);
loadWorkOrders();
//tried adding the value to the existing array by looping through each object,
// if I remove this, the code loads the data properly and works as it should,
// without the check if the objects have been edited.
ko.utils.arrayForEach(self.WorkOrders(), function (i) {
i.Edited = false
})
//S2:Method to Load all WorkOrders by making call to WEB API GET method
function loadWorkOrders() {
$.ajax({
type: "GET",
url: "/api/WorkOrderAPI",
success: function (data) {
self.WorkOrders(data);
},
error: function (err) {
alert(err.status + " from first get, are you connected to VPN?");
}
});
};
在此代码中我使用了
ko.utils.arrayForEach(self.WorkOrders(), function (i) {
i.Edited = false
})
尝试将Edited值添加到数组中。我认为错误实际上是我必须使用当前的数组创建一个新数组并将值编辑添加到数组中的每个对象...
另一种解决方案可能是在服务器端添加变量,但我认为这不会是最正确的#34;正确的"解。要使用以下方式查询数据:
// GET api/TimeRegistrationAPI
public IQueryable<TimeRegistration> GetTimeRegistration()
{
return db.TimeRegistration;
}
通过Knockout文档,我无法找到解决此问题的正确方法(参考文献http://knockoutjs.com/documentation/observableArrays.html)
提前感谢您的帮助
答案 0 :(得分:1)
您有异步加载,所以在您执行ko.utils.arrayForEach(...)
时,数组仍为空。要解决此问题,您需要从loadWorkOrders
返回承诺:
function loadWorkOrders() {
return $.ajax({
type: "GET",
url: "/api/WorkOrderAPI",
success: function (data) {
self.WorkOrders(data);
},
error: function (err) {
alert(err.status + " from first get, are you connected to VPN?");
}
});
};
然后在then
回调中迭代你的数组:
loadWorkOrders().then(function() {
ko.utils.arrayForEach(self.WorkOrders(), function (i) {
i.Edited = false
});
});