Kendo UI drop down not updated when Knockout view model updates

Kendo UI drop down not updated when Knockout view model updates

by Joe Wilson

HTML

<script src="http://cdn.kendostatic.com/2012.3.1114/js/kendo.all.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.1.js"></script>
<link rel="stylesheet" href="http://cdn.kendostatic.com/2012.3.1114/styles/kendo.common.min.css">
<link rel="stylesheet" href="http://cdn.kendostatic.com/2012.3.1114/styles/kendo.default.min.css">
<p>The fruitId should be "2" (orange) initially, then "3" (banana) after
    the button click. The text box and the drop down are bound to the same
    value in the Knockout view model (fruitId).</p>
<p>As the drop down is changed manually, the Knockout view model is updated,
    and the drop down and text box show the new value. But as the button is
    clicked and the view model is updated in code, the text box shows the correct
    value, but the drop down does not.</p>
<p>How can the drop down be set in code with Knockout?</p>
<p>
    <label for="kendoDropDown">Kendo UI Drop Down</label>
    <input id="kendoDropDown" type="text" data-bind="value: fruitId"
    />
</p>
<p>
    <label for="select">Plain old select</label>
    <select id="select" data-bind="value: fruitId">
        <option value="1">apple</option>
        <option value="2">orange</option>
        <option value="3">banana</option>
    </select>
</p>
<p>
    <label for="textBox">Plain old text box</label>
    <input id="textBox" type="text" data-bind="value: fruitId" />
</p>
<p>
    <button id="changeTo3" class="k-button">change fruitId to "3" (banana) programmatically</button>
</p>
<p>
    <button id="changeTo2" class="k-button">change fruitId to "2" (orange) programmatically</button>
</p>

CSS

p {
    margin-bottom: 20px;
}

JavaScript

// Init the drop down
$("#kendoDropDown").kendoDropDownList({
    dataValueField: "id",
    dataTextField: "name",
    dataSource: [
        { id: "1", name: "apple" }, 
        { id: "2", name: "orange" }, 
        { id: "3", name: "banana" }
    ]
});

// Kendo UI team work recommended around
//$("#kendoDropDown").bind("change", function() {
//    $(this).data("kendoDropDownList").select(this.selectedIndex);
//});

// Define and init the Knockout view model
var ViewModel = function () {
        var self = this;
        self.fruitId = ko.observable();
        // Real work around
        self.fruitId.subscribe(function (newValue) {
            $("#kendoDropDown").data("kendoDropDownList").value(newValue);
        });
    };
    vm = new ViewModel();   

// Set the initial fruit value
vm.fruitId("2"); // orange

// Wire up KO binding
ko.applyBindings(vm);

// Wire up the buttons
$("#changeTo3").click(function () {
    vm.fruitId("3"); // banana
});
$("#changeTo2").click(function () {
    vm.fruitId("2"); // orange
});