我正在尝试创建一个 KnockoutJS 视图模型,它为客户订单和许多订单项目建模。我想加载初始数据,并验证数据。
到目前为止,我可以使用 knockoutjs.mapping 加载数据,验证使用映射添加的数据。
// data to load into viewmodel
var modeldata = {
"OrderID":1,
"ReturnString":null,
"CustomerName":"First Customer",
"OrderDate":"2013-09-16T19:41:40.1639709+01:00",
"OrderItems": [
{"ItemID":0,
"ItemName":"Name_0",
"ItemPrice":0.0,
"_destroy":false
},
{"ItemID":1,
"ItemName":"Name_1",
"ItemPrice":10.0,
"_destroy":false
},
{"ItemID":2,
"ItemName":"Name_2",
"ItemPrice":20.0,
"_destroy":false
}
]
};
// setup defaults for validation
var validationOptions = {
insertMessages: true,
decorateElement: true,
errorElementClass: 'errorCSS',
messagesOnModified: true,
debug: true,
grouping: {
deep: true,
observable: false //Needed so added objects AFTER the initial setup get included
},
};
ko.validation.init(validationOptions);
// define array model
var Item = function () {
var self = this;
ItemID = ko.observable();
ItemName = ko.observable().extend({
required: { message: '* item name needed' }
});
ItemPrice = ko.observable();
_destroy = false;
}
// define view model
var ViewModel = function (data) {
var self = this;
self.OrderID = ko.observable();
self.ReturnString = ko.observable();
self.CustomerName = ko.observable().extend({
required: { message: '* customer name needed' }
});
self.OrderDate = ko.observable();
self.OrderItems = ko.observableArray([]); // to be array of "Item"
// create validation group
self.orderErrors = ko.validation.group(self);
self.orderItemErrors = ko.validation.group(
self.OrderItems, { deep: true }
);
self.lineItemsValid = function () {
var LValid = false;
if (self.orderItemErrors().length > 0) {
if (self.orderItemErrors()[0] != null) // important to test for null
LValid = false;
else
LValid = true;
}
else LValid = true
if (LValid) {
return true
}
else
{
self.orderItemErrors.showAllMessages();
return false;
}
}
self.orderValid = function () {
var LValid = false;
if (self.orderErrors().length > 0) {
if (self.orderErrors()[0] != null) // important to test for null
LValid = false;
else
LValid = true;
}
else LValid = true
if (LValid) {
return true
}
else {
self.orderErrors.showAllMessages();
return false;
}
}
self.isValid = function () {
if(self.orderValid() & self.lineItemsValid()){
alert('All ok!')
}
else{
alert('Errors!');}
}
// operations
self.addLineItem = function () {
self.OrderItems.unshift(new Item());
}
self.removeLineItem = function (item) {
self.OrderItems.destroy(item);
}
// load data into model
self.loadData = function () {
ko.mapping.fromJS(modeldata, {}, self);
}
}
$(document).ready(function () {
var viewModel = new ViewModel()
ko.applyBindings(viewModel);
});
问题:
(1) 我也可以使用点击功能添加订单项目,但这些数据似乎没有在可观察数组中更新。但是,当我调用“删除”项函数时,数组项被标记为已删除。
(2) 当我使用映射加载项目并测试验证(必需 = true)时,它仅适用于通过映射加载的项目,而不适用于我在映射完成后添加的订单项目
(3)当我更新一个映射引入的订单项时,变化立即反映在可观察数组中,当我更新映射后添加的一个订单项时,数组中没有更新。
我在这里有一个 JSFiddle:
http://jsfiddle.net/devops/ZsDjh/40/
我确信这与我如何添加到可观察数组有关,但看不到任何明显的东西 - 我显然缺少一些基本的东西......如果有人有任何想法?
谢谢