📜 ⬆️ ⬇️

How to auto-sync data while editing Kendo Grid cells

We want to share with all the translation of our recent article from Codeproject.com: “How to make data auto-synchronization while editing Kendo Grid cells” .

Kendo Grid uses a DataSource in which the autoSync property can be set to true. In this case, after editing the cell, it automatically updates the data in the database. But at the same time there is a big inconvenience: after we have edited one cell and click into another, Kendo Grid seems to open the editor in a new cell. But at this very moment there is an auto-sync (the Grid updates the data), and the editor disappears. You have to click twice in the second cell to make Kendo Grid edit it.

It would be desirable that when editing cells in the auto-synchronization mode, the behavior of Kendo Grid was similar to the generally accepted one, so that when you click on an edited cell, you can immediately edit it and not have to double-click it.
')
For this you need to do a lot.

1. Before initializing the Grid-a, you need to set the event handling:

var mouseDown = false; document.body.onmousedown = function() { mouseDown = true; } document.body.onmouseup = function() { mouseDown = false; } 

2. Then get 2 variables:

 var saved = false; var saved2 = false; 

saved is set when saving data to the DataSource, and saved2 is after synchronizing data with the remote database.

3. Set event handlers for edit and save in the Grid:

 edit: function(e) { if (saved) { saved = false; var grid = e.sender; var col = e.container.context.cellIndex; var row = e.container.context.parentNode.rowIndex; function resetEditor(){ if(!saved2) setTimeout(resetEditor,100); else{ saved2 = false; var cell = $(grid.tbody).find("tr:eq(" +row+ ") td:eq(" + col + ")"); grid.editCell(cell) grid.table.focus(); } }; resetEditor(); } }, save: function(e) { saved = true; saved2 = false; var grid = e.sender; function sync2db(){ if(mouseDown) setTimeout(sync2db,50); else{ setTimeout(function() { grid.dataSource.sync().then(function(){ saved2 = true; }); },10) } }; sync2db(); }, 

Kendo Grid triggers an edit event only after the mousesup system event. If synchronization occurs before this point, then event edit will be lost and the Grid will not put the editor in a new cell. Therefore, during the save event, we call the sync2db function, which, by timer, postpones synchronization until the event mouseup occurs.

But all this is not enough. After synchronization, the editor will still be lost (Kendo Grid behaves this way). Therefore, the edit handler remembers the cell being edited and, after synchronization, again puts it into edit mode. For this, the edit handler calls the resetEditor function, which waits for the timer when the saved2 variable is set after synchronization, and then re-puts the saved cell into edit mode. It doesn't look very simple, but it works great.

Source: https://habr.com/ru/post/273103/


All Articles