Skip to content

Instantly share code, notes, and snippets.

@samueljseay
Forked from heycarsten/ember.computed.stored.js
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samueljseay/f6e2d4a8811b869c2c86 to your computer and use it in GitHub Desktop.
Save samueljseay/f6e2d4a8811b869c2c86 to your computer and use it in GitHub Desktop.
###
Creates a computed property that persists into local storage, all
instances share the same value for the same property.
App.AuthController = Ember.Controller.extend({
token: Em.computed.stored()
});
controller = App.__container__.lookup('controller:auth')
controller.set('token', 'abc123foo456bar')
**Page is reloaded**
controller.get('token')
-> 'abc123foo456bar'
###
(->
keyFor = (obj, property) ->
ns = obj.constructor.toString()
ns + '.' + Em.String.underscore(property)
getItem = (obj, property) ->
key = keyFor(obj, property)
data = localStorage.getItem(key)
if data? then JSON.parse(data).data else null
setItem = (obj, property, value) ->
key = keyFor(obj, property)
if value is null
localStorage.removeItem(key)
return
else
localStorage.setItem(key, JSON.stringify(
data: value
))
value
Em.computed.stored = ->
Em.computed((key, value) ->
if arguments.length is 1
getItem(this, key)
else
setItem(this, key, value)
value
)
return
)()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment