Caching a Kendo DataSource Using LocalStorage

I am using ComboBox Kendo UI with an external XML DataSource. Here's the DataSource code:

try { var csDataSrc = new kendo.data.DataSource( { transport: { read: "Data/StateList.xml", dataType: "xml", create: { cache: true } }, schema: { type: "xml", data: "/States/State", model: { fields: { id: "id/text()", name: "name/text()" } } } }); csDataSrc.read(); } catch (err) { log.error(err.message); } 

This creates a data source, here is the code that creates the kendo combo box:

 $("#stateList").kendoComboBox( { index: 0, placeholder: "Begin typing Coverage State...", dataTextField: "name", dataValueField: "id", filter: "contains", dataSource: csDataSrc, text: $("#hdnStateName").val(), value: $("#hdnStateKey").val(), change: function(e) { $("#hdnStateKey").val(this.value()); $("#hdnStateName").val(this.text()); } }); 

This works very well, but the data for the real list is huge, and I would like to store it in local storage with something like this: localStorage.setItem ("state_key", csDataSrc); Then, when the page loads, rather than building and reading from the xml server all the time, I would like it to be something like this:

 var csDataSrc = localStorage.getItem("state_key"); if(csDataSrc === null) { // create the data source with the above code // and store it in localStorage. } 

Then tie it here ...

 ...kendoComboBox( { ..., .dataSource: csDataSrc, ... }); 

I am creating the data source in order, it seems to be stored correctly in localStorage, but when you leave the page and return, the data source is always zero. I see this using the Chrome Developer Tools resource tab, but it will not be bound to the combo box correctly. Any help or if I need to clarify anything to make this clearer please let me know

Thanks -s

+4
source share
1 answer

To do this, you can use a custom reading method ( link ).

 transport: { read: function(operation) { var cashedData = localStorage.getItem("moviesData"); if(cashedData != null || cashedData != undefined) { //if local data exists load from it operation.success(JSON.parse(cashedData)); } else { $.ajax({ //using jsfiddle echo service to simulate remote data loading url: '/echo/json/', type: "POST", dataType: "json", data: { json: JSON.stringify(data) }, success: function(response) { //store response localStorage.setItem("moviesData", JSON.stringify(response)); //pass the pass response to the DataSource operation.success(response); } }); } } } 

Here is a working example: http://jsfiddle.net/LnTe7/12/

+10
source

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


All Articles