使用jQuery更新下拉列表中的选定值后,如何更新底层绑定的KO数据<select>?



我正在使用jQuery更新数据绑定选择下拉列表的选定值$(item).val(newVal)然而,底层绑定的KO数据没有更新。有没有办法让绑定的数据也更新?

更新selectedIndex的javascript代码不知道数据模型

这里有一把小提琴,展示如何以正确的方式进行,你是如何进行的(坏的方式),以及如何按照你的要求进行(错误的方式:),以及使其工作的方法)

http://jsfiddle.net/Kohan/h4HLs/2/

Js

function vm() {
    var items = ko.observableArray(
           ['initial', 'changedModel', 'changedBroken', 'changedHacked']);
    var selectedItem = ko.observable();
    function changeModel(){
        selectedItem("changedModel");
    }
    function changeDropdown(){
        $("#selectBox").prop('selectedIndex', 2);
    }
    function changeDropdownHack(){
        $("#selectBox").prop('selectedIndex', 3);
        $("#selectBox").change();
    }
    return {
        items: items,
        selectedItem: selectedItem,
        changeModel: changeModel,
        changeDropdown: changeDropdown,
        changeDropdownHack: changeDropdownHack
    }
};
ko.applyBindings(vm);

html

<select id="selectBox" data-bind="options: items, value: selectedItem"></select>
<h2>Selected Value: </h2>
<div data-bind="text: selectedItem"></div>
<button data-bind="click: changeModel">change Model</button><br />
<button data-bind="click: changeDropdown">change Dropdown With Jquery (Broken)</button><br />
<button data-bind="click: changeDropdownHack">change Dropdown With Jquery + Hack</button><br />

您能提供一些代码吗?

如果除了options绑定之外还使用value绑定,KO视图模型会自动更新:

<select data-bind="options: myOptions, value: myValue"></select>

您应该在viewModel中插入附加值
检查下拉列表的值数组是否为.obstatibleArray
如果是调用.valueHasMutted(),则在更新之后
你可以像这个一样选择你的淘汰上下文

var knockoutContect = ko.contextFor($('#yourDropDown'));

就像4imble已经说过的,只使用淘汰赛更好/更容易。所以你会得到类似viewModel.dropdownObservable(newVal)的东西,而不是$(item).val(newVal)

如果这对你来说不是一个选项,你可以在select的更改事件上更新视图模型:

ko.applyBindings({
    value: ko.observable(1)
});
var $select = $('#select');
// update the ViewModel value on change
$select.change(function() {
    ko.contextFor(this).$data.value($select.val());
});
// change the value and trigger the change event
$select.val(2).trigger('change');

请参阅http://jsfiddle.net/sjroesink/P83kz/

最新更新