如何刷新'选项'ko多选组件中的绑定

How to refresh the 'options' binding in an ko multi select component?

本文关键字:组件 绑定 ko 选项 刷新 何刷新      更新时间:2024-05-21

我有一个多选组件,我用"options"绑定将其绑定,然后根据我在其他多选组件中选择的值刷新"options’。下面是第一个多选组件

<select data-bind="multiple: true, required: true, options:repositoriesForSelect, value: selectedRepository"></select>

基于在该组件中选择的值,我正在刷新第二个组件的选项

<select data-bind=" multiple: true,required: true,options: branchesForSelect,value: selectedBranch"></select>

使用计算的变量刷新第二个选项:

 branchesForSelect = ko.computed(function(){
   //selectedRepository is an observable array here
  //some logic
 });

这很好,但除此之外,我还想根据在同一组件中选择的值刷新"branchesForSelect"。也就是说,如果"branchesForSelect"包含值"A"、"B"、"C",则在选择"A"时,我希望刷新"branchesForSelect"以在选项列表中仅显示"C"。

有人能指引我吗?如果问题不清楚,请在评论中告诉我。

感谢

通过计算第二个选项列表,您走上了正确的轨道。这就是您仍然需要做的:在计算的内部,使用selectedRepository的值返回链接到所选内容的选项数组。通过使用此值,淘汰将确保在第一个选择的value变量更改后,重新评估第二个选项列表。

在评论中澄清问题后:

从用户体验的角度来看(如果你问我的话),在用户输入后更改select本身的值是个坏主意,但肯定可以做到。下面的代码将向您展示如何操作。当多选的第一个选项处于活动状态时,其他选项将被隐藏。

这里有一个例子:

var repositoryBranches = {
  a: ["All", 1, 2, 3, 4, 5, 6],
  b: ["All", 0, 7, 8],
  c: ["All", 9, 10]
};
var VM = function() {
  var self = this;
  
  this.repositoryKeys = ["a", "b", "c"];
  this.selectedRepository = ko.observable("a");
  
  this.selectedBranches = ko.observableArray([]);
  this.branchesForSelectedRepository = ko.computed(function() {
    var allBranchesForRepo = repositoryBranches[self.selectedRepository()];
    // We're making an exception if the first one is selected:
    // don't show any other options if the selected one is the first one
    if (self.selectedBranches()[0] === allBranchesForRepo[0]) {
      return ["All"];
    }
  
    return allBranchesForRepo;
  });
 
  // Clear selection when changing repository
  this.selectedRepository.subscribe(function clearSelection() {
    self.selectedBranches([]);
  });
};
ko.applyBindings(new VM());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<select data-bind="options:repositoryKeys, value: selectedRepository">  </select>
<select multiple="true" data-bind="options:branchesForSelectedRepository, selectedOptions: selectedBranches"></select>

(小提琴)

如果您需要帮助,请告诉我找到一种将"分支"链接到"存储库"的好方法。理想情况下,"存储库"有自己的模型,其中包含一组"分支"。然后,您就可以定义您的计算数组,类似于return self.firstSelection().branches;