2013-03-16 82 views
5

我有一個應用程序,它使用ember-rails gem與rails應用程序交互。Ember.js應用程序離線行爲

我想使用localStorage的轉接器來存儲產品列表,一旦他們已經從服務器通過REST API下載。

然後,如果應用程序處於脫機狀態,燼可以使用localStorage的數據,而不是要求數據的Rails應用程序。

有沒有辦法做到這一點?

+0

一種方法可能是創建自己的模型對象,而不是使用餘燼數據... – thecodejack 2013-03-17 18:04:29

+0

但是我想使用ember-data的功能。我希望能夠將REST API中的數據無縫地加載到一堆ember模型類中,而無需編寫任何代碼。在它的生命週期中甚至有可能在應用程序中切換數據存儲? – l33z3r 2013-03-19 10:24:37

回答

3

我已經做了一些沿着這些線。這不處理何時刷新緩存,以及類似的事情。但是,它將爲您提供一種初始加載localStorage項目的方法,然後如果網絡不可用,則內容將保持爲本地數據。你當然可以大大擴展這個來處理你的需求。

App.PhotoCategories = Ember.Object.extend 

    init: -> 
    @_super() 
    @loadPhotoCategories 

    loadPhotoCategories:() -> 
    # load cached categories from local storage 
    @set 'content', @getFromCache("photoCategories") 

    if @content? 
     if @content.length == 0 
     $.ajax 
      type: "POST"  
      url: "/api/getCategories" 
      success: (data) => 
      if !data.error 
      @set 'content', [] 

      for category in data 
       @pushObject category 

       # save categories to local storage 
       @saveToCache("photoCategories", @content)    

    saveToCache: (key, data) -> 
    if @supportsHtml5Storage() 
     localStorage.setItem(key + '_LastUpdatedAt', new Date()) 
     localStorage.setItem(key, JSON.stringify(data)) 
     true 
    else 
     false 

    getFromCache: (key) -> 
    if @supportsHtml5Storage() 
     data = localStorage[key] 

     if data? 
     JSON.parse(localStorage[key]) 
     else 
     null 
    else 
     null 

    supportsHtml5Storage: -> 
    try 
     return "localStorage" of window and window["localStorage"] isnt null 
    catch e 
     return false 
+1

乾杯,我會試試這個! – l33z3r 2013-04-17 10:22:53