简体   繁体   English

不要更新所有选择框-淘汰赛JS

[英]Dont update all select boxes - knockout js

Consider the following: 考虑以下:

self.selected = ko.observable();
self.selectionItems = ko.observableArray([{name: "bob"}, {name: "sally"}]);
self.containers = ko.observableArray([{name: "container 1", key:1}, {name: "container 2", key: 2}]);

If I have the following html: 如果我有以下html:

<div data-bind="foreach: containers">
  <div>
    <select data-bind="options: $parent.selectionItems, optionsText: 'name', optionsValue: 'name', value: $parent.selected"></select>
  </div>
</div>

Then when one of the containers has an item selected all the containers update to reflect the fact that in container x you selected a name of bob. 然后,当其中一个容器中的一项被选中时,所有容器都会更新,以反映在容器x中选择了鲍勃名称的事实。

How do I make actions like observables specific to that container element? 如何针对该容器元素执行类似可观察对象的操作?

essentially, if I have 20 containers via the self.containers each container should observe it own actions. 本质上,如果我通过self.containers有20个容器,则每个容器都应观察其自身的行为。 Would I make self.selected into an observableArray ? 我会把self.selected变成一个observableArray吗?

If you bind the value of every select to the same observable, they're all going to have the same value. 如果将每个选择的value绑定到相同的可观察对象,则它们将都具有相同的值。 You would need to have an observable in the containers object to store the selected. 您需要在containers对象中具有一个observable来存储所选内容。

self.containers = ko.observableArray([{
  name: "container 1",
  key: 1,
  selected: ko.observable()
}, {
  name: "container 2",
  key: 2,
  selected: ko.observable()
}]);

Alternatively, you could have an observableArray of selecteds in the parent, but that would require you to coordinate the size of your array to be the same length as containers and you'd have to use $index to get the right one; 另外,在父级中可能有一个observableArray of selecteds,但是这需要您将数组的大小调整为与containers相同的长度,并且必须使用$index来获取正确的数组。 it's a clunkier option. 这是一个笨拙的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM