更新源数组后,Knockout 下拉列表不更新

Knockout dropdown not updating after source array is updated

我有一个从视图模型的可观察数组填充的下拉列表。有一个按钮数据绑定到一个函数,该函数从数组中删除一个元素。单击按钮时,数组会进行移位以删除元素。但是下拉不反映变化,下拉值不变。

html:

<!-- ko if: t -->
<select data-bind="template: { name: 'selectTemplateType', data: t }, value: selectedId"></select>
<!-- /ko -->
<!-- ko ifnot: t -->
<select>
    <option>No templates loaded</option>
</select>
<!-- /ko -->
<div data-bind='text: selectedId'></div>

<script type="text/html" id="selectTemplateType">
    <!-- ko foreach: groups -->
        <optgroup data-bind="attr: { 'label': name }, foreach: types">
            <option data-bind="value: id, text: name"></option>
        </optgroup>
    <!-- /ko -->
</script>

<div>
<button type="button" data-bind="click: remove">Remove First</button>
</div>

javascript:

var t = {
    groups: [
        { name: 'a', types: [{id: 1, name: 't1'}] },
        { name: 'b', types: [{id: 102, name: 't2'}, {id: 103, name: 't3'}] },
        { name: 'c', types: [{id: 5, name: 'x'}] }
    ]
}
var ViewModel = function() {
    var me = this;
    let temp = {
      groups: [
          { name: 'a', types: [{id: 1, name: 't1'}] },
          { name: 'b', types: [{id: 102, name: 't2'}, {id: 103, name: 't3'}] },
          { name: 'c', types: [{id: 5, name: 'x'}] }
      ]
      };
    me.t= ko.observable(ko.mapping.fromJS(temp));
    me.selectedId= ko.observable(103);
    
    me.remove = function(){
        me.t().groups().shift();
    }
};
var vm = new ViewModel();
ko.applyBindings(vm);

您可以在此处看到混乱情况: http://jsfiddle.net/Eves/2kw9y37t/24/

我想我错过了一些愚蠢的事情。有人知道我错过了什么吗?

如果您查看 Observable Arrays 中的文档,您可以阅读以下内容:

pop, push, shift, unshift, reverse, sort, splice

All of these functions are equivalent to running the native JavaScript array functions on the underlying array, and then notifying listeners about the change

当你这样做时:

me.t().groups()

你正在对底层数组进行操作,然后:

me.t().groups().shift();

它工作正常,但是你没有通知听众有关更改,并且你的 html.

中没有任何变化

你可以这样写:

me.t().groups.shift();

即在observable数组中调用Knockout提供的shift()方法。请注意 groups 没有括号。