Search code examples
knockout.jskendo-gridknockout-kendo

knockout-kendo.js data binding issue


I am using knockout-kendo.js for knockout.js binding to kendo grid. If you bind object's first level property then it works fine. Here is a sample - http://jsfiddle.net/rniemeyer/jZtg5/

In the above example items property is defined in the viewmodel (i.e. ViewModel.Items)

However If you use object's second level property to bind it to kendo grid, then it doesn't work. Here is a sample where binding doesn't work - http://jsfiddle.net/thakkar/QhF2W/3/

In this example, the items property is not directly defined in the viewmodel. Instead it is a property of an object which is used in the viewmodel. (i.e. ViewModel.obj.Items)

var Item = function(id, name, type) {
    this.id = id;
    this.name = ko.observable(name);
    this.type = type;
};

var vm2 = function() {
    this.items = ko.observableArray([
        new Item(1, "one", "a"),
        new Item(2, "two", "b"),
        new Item(3, "three", "a")
    ]);

var ViewModel = function() {
    this.obj = ko.observable(new vm2())
};

ko.applyBindings(new ViewModel());

Solution

  • Here is an updated fixed Fiddle:

    http://jsfiddle.net/DianaNassar/z439C/2/

    Basically, you were missing a curly brace [you had a console error]. But the main thing is, if you want to drill down two levels you had to bind the grid like this:

    kendoGrid: {data:obj().items(),scrollable: false,columns: [
                                { field: 'id', title: 'id', width: 150 },
                                { field: 'name', title: 'name' },
                                { field: 'type', title: 'type' }
                            ] } "
    

    Not:

    kendoGrid: {data:obj.items,scrollable: false,columns: [
                                { field: 'id', title: 'id', width: 150 },
                                { field: 'name', title: 'name' },
                                { field: 'type', title: 'type' }
                            ] } "
    

    Knockout observables are functions, you set their value by passing the new value as an argument to the function, and you read it by passing no arguments.

    I hope this helps.