-
-
Save samueljseay/f6e2d4a8811b869c2c86 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### | |
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