I am using RPNiemeyer`s kendo-knockout library. I have a kendo grid with a kendo template in it. In the template there is a button which uses knockout click binding which calls a method that changes the viewModel. Steps to reproduce:
- Click the button in the grid.
- A method is called that changes the property of the viewModel and alerts the new value.
- Click the button again. The button is not working any more.
Note: If You remove the line that changes the property of the viewmodel everything is working fine.
Please explain the reason why this is not working and any ideas and solutions will be greatly appreciated. Thank You!
html:
<div id="grid" data-bind="kendoGrid: { data: fruits, columns: [
{
field: 'name',
title: 'Fruit',
width: 50
},
{
template: '<button class=\'k-button\' data-bind=\'click: function() { changeFruit() }\' >Change Fruit Name</button>',
width: 30
}
],
scrollable: false, sortable: true, pageable: false }" style="height: 380px">
</div>
javascript:
var ViewModel = function() {
this.fruit1 = {
color: ko.observable("green"),
name: ko.observable("apple"),
};
this.fruit2 = {
color: ko.observable("orange"),
name: ko.observable("orange"),
};
this.fruits = ko.observableArray([
this.fruit1,
this.fruit2
]);
this.changeFruit = function() {
// this line breaks the binding,
// when You change the property of the viewModel
// You cannot call this function any more
this.fruits()[0].name("Test");
alert(this.fruits()[0].name());
}
};
ko.applyBindings(new ViewModel());
Using Knockout templates inside of the grid is not fully supported at this point. Right now your row is bound, because the elements are there when Knockout first passes over the document to apply bindings.
After the data is updated, the rows are re-rendered and the bindings are lost.
One fix is to use an event handler for the "dataBound" event that rebinds the table. This could be done globally, something like:
Here is a sample: http://jsfiddle.net/rniemeyer/5Zkyg/
I also added a custom binding that prevents Knockout from binding the table on the first pass, so that it is not bound twice (once overall applyBindings and once from the dataBound handler.
Ultimately, this is something that I want to support better in Knockout-Kendo and it is the next thing that I plan to work on with the library.
Here is a sample of how it might work from a branch that I had started a while back: http://jsfiddle.net/rniemeyer/xBL2B/