1
votes

I have a Kendo UI drop down that is not updating its UI when the Knockout view model it is bound to changes. I can get a plain HTML select and a plain text box to show the new model values, but not the Kendo UI one. What am I overlooking?

Here's a code sample (and JSFiddle). The fruitId should be "2" (orange) initially, then "3" (banana) after the button click. The text box and the two drop downs are bound to the same value in the Knockout view model (fruitId).

As the Kendo UI drop down is changed manually, the Knockout view model is updated, and the plain 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 and plain drop down show the correct value, but the Kendo UI drop down does not.

The HTML

<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" class="k-textbox" />
</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>

The JavaScript

// Define the Knockout view model
var ViewModel = function (data) {
    var self = this;
    self.fruitId = ko.observable(data.fruitId);
}

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

// Wire up KO bindidng
var initialData = { fruitId: "2" };
ko.applyBindings(new ViewModel(initialData));

// Wire up the buttons
$("#changeTo3").click(function () {
    var newData = { fruitId: "3" };
    ko.applyBindings(new ViewModel(newData));
});
$("#changeTo2").click(function () {
    var newData = { fruitId: "2" };
    ko.applyBindings(new ViewModel(newData));
});
2

2 Answers

1
votes
0
votes

I ended up using Knockout subscriptions for now instead of the Knockout-Kendo library. I set the drop down value in the UI inside the subscription function.

I also had to change the code above to keep the same instance of the ViewModel in memory. Getting a new ViewModel() on each button click meant the change/subscription code didn't fire.