2012-10-19 98 views
4

我現在用的是劍道UI組合框與外部數據源XML劍道UI DataSource對象。這裏的數據源代碼:緩存使用本地存儲

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); 
} 

創建該數據源,這裏是一個創建劍道組合框代碼:

$("#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()); 
    } 
}); 

這個作品真的很好,但對於真正的列表中的數據是巨大的,我倒要它像這樣的東西存儲在本地存儲: localStorage.setItem(「state_key」,csDataSrc); 然後當頁面加載,而不是建設,並從服務器端XML閱讀所有的時間,我想爲它是這樣的:

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

然後將其綁定在這裏......

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

我創建數據源精細,它似乎正確地存儲在localStorage的,但是當你離開頁面,回來的數據源總是空。我可以看到它使用的Chrome開發人員工具的資源選項卡,但它不會綁定到組合框正確。 任何幫助,或者如果我需要闡述什麼,使之更清楚,請讓我知道

感謝 -s

回答

10

爲了實現這一目標,您可以使用自定義的閱讀方法(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's 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); 
       } 
      }); 
     }     
    } 
} 

這裏是一個工作示例:http://jsfiddle.net/LnTe7/12/