1

这是小提琴: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);
4

1 回答 1

5

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 */
};
于 2013-03-20T00:36:30.273 回答