Ember.js应用程序脱机行为

Ember.js应用程序脱机行为,ember.js,ember-data,Ember.js,Ember Data,我有一个使用ember rails gem与rails应用程序交互的ember应用程序 我希望在通过RESTAPI从服务器下载产品后,使用localStorage适配器存储产品列表 然后,如果应用程序处于脱机状态,ember可以使用localStorage数据,而不是向rails应用程序请求数据 有什么方法可以做到这一点吗?我已经按照这些思路做了一些事情。这不能处理何时刷新缓存之类的事情。但是,它将为您提供一种从localStorage开始加载项目的方法,如果网络不可用,内容将作为本地数据保留。

我有一个使用ember rails gem与rails应用程序交互的ember应用程序

我希望在通过RESTAPI从服务器下载产品后,使用localStorage适配器存储产品列表

然后,如果应用程序处于脱机状态,ember可以使用localStorage数据,而不是向rails应用程序请求数据


有什么方法可以做到这一点吗?

我已经按照这些思路做了一些事情。这不能处理何时刷新缓存之类的事情。但是,它将为您提供一种从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

一种方法可能是创建您自己的模型对象,而不是使用余烬数据…但是,我想使用余烬数据的功能。我希望能够无缝地将RESTAPI中的数据加载到一堆ember模型类中,而无需编写任何这样做的代码。在你的应用程序的生命周期中,是否有可能关闭数据存储?干杯,我来试试!