这是小提琴:http://jsfiddle.net/7RDc3/2096/
“添加服务”按钮不起作用。我需要它来镜像“添加硬件”按钮的功能。
我的以下代码出了点问题:不过,您可以在上面的小提琴中看到它的运行情况。
var viewModel = function(hardware, services) {
var self = this;
self.hardwares = ko.observableArray(hardware);
self.services = ko.observableArray(services);
self.addHardware = function() {
self.hardwares.push({
name: "",
price: ""
});
};
self.removeHardware = function(hardware) {
self.hardwares.remove(hardware);
};
self.addService = function() {
self.services.push({
name: "",
price: ""
});
};
self.removeService = function(services) {
self.services.remove(services);
};
self.save = function(form) {
var allModel = [];
ko.utils.arrayForEach(services(), function (service) {
allOrders.push(ko.toJS(service));
});
ko.utils.arrayForEach(hardwares(), function (hardware) {
allOrders.push(ko.toJS(hardware));
});
alert("Could now transmit to server: " + ko.utils.stringifyJson(allOrders));
};
};
var FinalViewModel = new viewModel([]);
ko.applyBindings(FinalViewModel);
最佳答案
构造视图模型时,您没有为services
参数传递参数:
var FinalViewModel = new viewModel([], []);
ko.applyBindings(FinalViewModel);
更新的小提琴:http://jsfiddle.net/7RDc3/2097/
如果未提供参数,您还可以扩展构造函数以使用空数组:
var viewModel = function(hardware, services) {
var self = this;
self.hardwares = ko.observableArray(hardware || []);
self.services = ko.observableArray(services || []);
/* snip */
};
关于javascript - knockout JS foreach网格不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15513087/