Skip to content Skip to sidebar Skip to footer

Knockout-kendo Issues Binding Through Computed Observable

I am attempting to use knockout-kendo.js to declare a kendo dropdownlist control in a knockout forEach template, so that as new items are added to the knockout observable array, ne

Solution 1:

Let me offer you some advice. Try to avoid accessing properties of an observable's value, as you can see, the dependency detection will not always be able to detect the dependency. You should create a computed observable which does the accessing for you.

var ViewModel = function () {
    // ...

    this.selectedChoice = ko.computed(function () {
        var id = this.selectedId();
        return ko.utils.arrayFirst(this.choices(), function(choice) {
           return choice.id ===  id;
        });
    }, this);
    this.selectedChoiceShapes = ko.computed(function () {
        var selectedChoice = this.selectedChoice();
        return selectedChoice && selectedChoice.shapes;
    }, this);
}

Then your bindings becomes:

<input data-bind="kendoDropDownList: {
                      dataTextField: 'name',
                      dataValueField: 'id',
                      data: choices,
                      value: selectedId }" />
<input data-bind="kendoDropDownList: {
                      dataTextField: 'caption',
                      dataValueField: 'id',
                      data: selectedChoiceShapes,
                      value: selectedShapeId }" />

updated fiddle


Solution 2:

This appears to be a shortcoming of Kendo using Knockout. When Kendo evaluates selectedChoice().shapes it holds onto the array it finds, instead of keeping the entire expression. If you update that specific array with options, you can see them in the second dropdown. The problem is that when you update selectedChoice Kendo does not reevaluate the data to the new shapes array. You can see this behavior in this fiddle.

Open the JS console, set the context to the fiddle (it defaults to the top frame in Chrome`, and run this:

window.vm.choices()[1].shapes.push({"id": "6", "caption" : "Thing"})

And you will see the second dropdown update. Changing the first dropdown doesn't have an effect. You can see that in this fiddle Knockout without kendo reevaluates the entire expression, properly updating the second select options.


Post a Comment for "Knockout-kendo Issues Binding Through Computed Observable"