Knockout js foreach grid不工作

时间:2013-03-20 00:27:45

标签: javascript knockout.js

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

1 个答案:

答案 0 :(得分: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 */
};