Arjen van Putten
Arjen van Putten

Reputation: 23

Kendo-Knockout: Binding "selected" viewmodel property with grid

Im using RPNiemeyer`s kendo-knockout library to bind my viewmodel with my KendoUI grid. What I would like to do is to subscribe to the change event of the grid, so I can update the corresponding viewmodel item.

I bound an observableArray with object's that look like this:

{
  Address: "Street name"
  ClientNumber: 1337
  NamePartner: "Client name"
  Selected: false
}

Now, I would like the Selected property to be set to true when the corresponding row is selected (the change event of the KendoUI grid). To do this I think I should be using the Knockoutjs custom binding handler.

I found this http://jsfiddle.net/D3rSk/155/, that is doing kind of the same. The only problem is that this example gives some error's in my console, also it is binding a separate 'selectedItem' observable, while I would like to bind it to the property within my observableArray.

Thanks in advance.

Upvotes: 2

Views: 4252

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

It is not completely seamless to do what you want, but you can do this:

  • add a handler for the change event
  • get the selected row element using the grid's select method
  • from the row element get the data item using the grid's dataItem method
  • this dataItem is a clean object, so take its unique key (ClientNumber in your case) and use it to find the original item in your observableArray.

Something like:

<div id="grid" data-bind="kendoGrid: { data: items, sortable: true, selectable: true, change: updateSelected, columns: ['Address', 'ClientNumber', 'NamePartner'], widget: grid }"></div>

With an updateSelected method on your view model like:

updateSelected: function() {
    var grid = viewModel.grid(),
        row = grid.select(),
        clientNumber = grid.dataItem(row).ClientNumber,
        actualItem = ko.utils.arrayFirst(viewModel.items(), function(item) {
           return item.ClientNumber === clientNumber;
        });

    if (actualItem) {
        actualItem.Selected = true;

        if (viewModel.previouslySelected) {
            viewModel.previouslySelected.Selected = false;   
        }

        viewModel.previouslySelected = actualItem;
    }            

    return true;
}

Sample: http://jsfiddle.net/rniemeyer/7MXfj/

You could consider attempting to move this logic into a custom binding that would be added next to the kendoGrid binding.

Upvotes: 5

Related Questions