Ember.js app离线行为

前端之家收集整理的这篇文章主要介绍了Ember.js app离线行为前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个使用ember-rails gem与rails应用程序交互的ember应用程序.

我想使用localStorage适配器来存储从服务器通过其余api下载产品的列表.

然后,如果应用程序处于脱机状态,则ember可以使用localStorage数据,而不是向rails app询问数据.

有没有办法做到这一点?

解决方法

我已经按照这些方针做了一些事情.这不会处理何时刷新缓存以及类似的事情.但是,它将为您提供一种从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

猜你在找的JavaScript相关文章