0

我有一个 foreach 绑定

<table id="Table_OperationsGroup">
    <tbody data-bind="foreach: groupOperationsGroup">
        <!-- ko if: $index() < $root.groupOperationsGroup().length - 1 -->
        <tr>
            <td>
                <select data-bind="changeGroup: groupOperations,options: operators, optionsText: 'Name', value: groupOperations" style="width: 105px;margin-top:5px !important;margin-bottom:5px !important;margin-left:0px !important;"></select>
            </td>
        </tr>
        <!-- /ko -->
    </tbody>
</table>

JS

ko.bindingHandlers.changeGroup = {
    update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        //some code to work with the select
    }
};


var groupOperationsTemplate = function () {
    var self = this;
    self.groupOperations = ko.observable(operators);
    self.lines = ko.observableArray([{
        operations: ko.observable()
    }]);
    self.addLine = function (line) {
        line.lines.push({
            operations: ko.observable(operators)
        })
    };
    self.removeLine = function (line) {
        if (self.lines().length > 1) {
            self.lines.remove(line);
        }
    };
};

var Filter = function () {
    var self = this;
    //self.template = ko.observableArray();    
    self.groupOperationsGroup = ko.observableArray([new groupOperationsTemplate()]);
    self.addGroupOperator = function (data) {
        self.groupOperationsGroup.splice(self.groupOperationsGroup.indexOf(data) + 1, 0, new groupOperationsTemplate());
    };
};

var vm = new Filter();
ko.applyBindings(vm);

所以,我想要的是,如果有人更改了选择,我想准确地选择绑定处理程序中正在更改的选择。问题是,每次选择都会调用绑定处理程序。它从 0 开始,然后是 1、2、3,依此类推。我希望你明白我的意思。

4

1 回答 1

1

让我们在这里讨论。

操作符是一个数组,你用它来绑定选择

self.groupOperations = ko.observable(operators);

代替

self.groupOperations = ko.observableArray([ { "Name": "Und", "Wert": 0 }, { "Name": "Und nicht", "Wert": 1 }, { "Name": "Oder", "Wert": 2 }, { "Name": "Oder nicht", "Wert": 3 } ]);
self.selectedValue = ko.observable();

self.selectedValue.subscribe(function( newValue) {
   //do whatever you want with new value
});

绑定选择时

 <!-- ko if: $index() < $root.groupOperationsGroup().length - 1 -->
        <tr>
            <td>
                <select data-bind="options: groupOperations, optionsText: 'Name', value: selectedValue" style="width: 105px;margin-top:5px !important;margin-bottom:5px !important;margin-left:0px !important;"></select>
            </td>
        </tr>
 <!-- /ko -->
于 2013-10-07T12:07:50.747 回答