Ember.js Offline Browser Behavior

I have an ember application that interacts with a rails application using the ember-rails stone.

I would like to use the localStorage adapter to store the list of products after they are downloaded from the server on top of the rest of the api.

Then, if the application is disconnected, ember can use localStorage data rather than requesting a rails application for data.

Is there any way to do this?

+5
source share
1 answer

- . . 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
+3

All Articles