I have an ember app that interacts with a rails app using the ember-rails gem.
I would like to use the localStorage adapter to store a list of products once they have been downloaded from the server over the rest api.
Then, if the app is offline, ember can use the localStorage data rather than asking the rails app for the data.
Is there a way to do this?
I have done something along these lines. This doesn't handle when to refresh for caching, and things like that. But, it will provide you with a way to initially load up items from localStorage and then if the network is not available, the content will just stay as the local data. You can of course expand this greatly to handle your needs.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With