KnockoutJS选项列表值与订阅



我在另一个列表中有一个下拉列表,可以向其中添加项目,然后用户可以通过更改下拉列表来更改他们添加的项目。

这在这里有效,当我添加一个项目时,在下拉列表中选择了正确的值:

<tbody data-bind="foreach: items">
<tr>
    <td>
        <select data-bind="
            options: materials,
            optionsValue: 'MaterialName',
            optionsText: function(item) {
                return item.MaterialGroup + ': ' + item.MaterialName;
            },
            optionsCaption: '[Choose a Material]',
            value : selectedMaterial(),
            attr: { name: 'MaterialOrderLine[' + $index() + '].MaterialName' }"></select> 
    </td>
    ...

所有这些目前都很好用。 但是现在我的挑战是,当下拉列表的选定值发生变化时,我现在需要在此下拉列表中添加一个订阅以执行其他操作,我认为我可以轻松做到这一点,但是此处的订阅不起作用:

function MaterialItem(material, qty) {
    var self = this;
    self.materials = ko.observableArray([]);
    //this populates the dropdown lists inside the grid
    $.when(
        $.ajax({
            url: '...',
            dataType: 'JSON',
            type: 'POST',
            data: JSON.stringify({... }),
            contentType: 'application/json; charset=utf-8'
        })
    ).done(function (result) {
        for (var i = 0; i < result.length; i++) {
            self.materials.push(result[i]);
        }
    });
    self.material = material;
    self.qty = qty;
    self.selectedMaterial =  ko.observable(material); //used to hold selected value on mat'l dropdown
    this.selectedMaterial.subscribe(function (newValue) {
        alert('f');
    }.bind(self));

}

此订阅根本不起作用。 但是,我可以通过更改我的 HTML 来让它工作:来自 "值 : 选定材料()"到"值:所选材料"

但是当我进行该更改时,下拉列表中的值不再正确设置(它默认为选择列表中的第一项)。

我认为是函数中未设置的挖空值的副本

选项列表是在可观察值之后设置的,因此当绑定选择时,所选材料可观察量已被重置。

其他一些事情...

  • 不要在循环中调用 observableArray 的推送,这将导致所有绑定重新触发每个操作。 调用拼接或仅设置数组值。

  • 你不需要使用 bind(self)。 所有这些所做的只是将函数内部的环境"this"设置为引用"self"。 你已经在变量中捕获了自我,所以只有我们。


.done(function (result) {
    self.materials(result);
    self.selectedMaterial(self.material);
}