[英]knockout.js updating a select list does not fire on first change
I have 2 select lists and I want to sync the index, so when the first has an index of 1 the second will have an index of 1 etc. 我有2个选择列表,我想同步索引,所以当第一个索引为1时,第二个索引为1等。
This is my html. 这是我的HTML。
<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/2.2.0/knockout-min.js"></script>
<div>
<select id="selLight" data-bind="options: $root.ddlLight, value: ddlLightSelected"></select>
<select id="selAction" data-bind="options: $root.ddlAction, value: ddlActionSelected"></select>
</div>
and the javascript... 和javascript ...
var ViewModel = function() {
var self = this;
self.ddlLight = ko.observableArray(["RED", "AMBER", "GREEN"]);
self.ddlAction = ko.observableArray(["STOP", "READY", "GO"]);
self.ddlLightSelected = ko.observable();
self.ddlActionSelected = ko.observable();
self.ddlLightSelected.subscribe(function (event) {
document.getElementById("selAction").selectedIndex =
self.ddlLight.indexOf(self.ddlLightSelected());
});
self.ddlActionSelected.subscribe(function (event) {
document.getElementById("selLight").selectedIndex =
self.ddlAction.indexOf(self.ddlActionSelected());
});
};
ko.applyBindings(new ViewModel());
I have a fiddle with the exact problem... 我有一个问题确切的问题......
http://jsfiddle.net/phykell/2vUTw/ http://jsfiddle.net/phykell/2vUTw/
EDIT: I was having a few problems with jsfiddle, so here is a jsbin... http://jsbin.com/ilomer/4/ 编辑:我有一些jsfiddle的问题,所以这里是一个jsbin ... http://jsbin.com/ilomer/4/
...and here's how to recreate the issue: ......以下是重建问题的方法:
The problem is this line of code: 问题是这行代码:
document.getElementById("selAction").selectedIndex = self.ddlLight.indexOf(self.ddlLightSelected());
You're directly changing the DOM, not allowing Knockout to kick off the observable pattern. 您正在直接更改DOM,不允许Knockout启动可观察模式。
If you want something to change, always change the ko.observable
, not the JavaScript variable or the DOM. 如果您想要更改某些内容,请始终更改
ko.observable
,而不是JavaScript变量或DOM。 Knockout will recognize the change, and therefor change the DOM itself. Knockout将识别这一变化,并因此改变DOM本身。 The solution would be:
解决方案是:
self.ddlLightSelected.subscribe(function (event) {
var index = self.ddlLight.indexOf(self.ddlLightSelected());
self.ddlActionSelected(self.ddlAction()[index]); // Update the Observable, not the DOM
});
self.ddlActionSelected.subscribe(function (event) {
var index = self.ddlAction.indexOf(self.ddlActionSelected());
self.ddlLightSelected(self.ddlLight()[index]); // Update the Observable, not the DOM
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.