Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save richardkmichael/f6d9db92f157053ab9d8 to your computer and use it in GitHub Desktop.
Save richardkmichael/f6d9db92f157053ab9d8 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')
contorller.set('token', 'abc123foo456bar')
**Page is reloaded**
controller.get('token')
-> 'abc123foo456bar'
*/
void function() {
function keyFor(obj, property) {
var ns = obj.constructor.toString();
return ns + '.' + Em.String.underscore(property);
}
function getItem(obj, property) {
var key = keyFor(obj, property),
data = localStorage.getItem(key);
if (data) {
return JSON.parse(data).data;
} else {
return null;
}
},
function setItem(obj, property, value) {
var key = keyFor(obj, property);
if (value === null) {
localStorage.removeItem(key);
} else {
localStorage.setItem(key, JSON.stringify({ data: value }));
}
return value;
}
Em.computed.stored = function() {
return Em.computed(function(key, value) {
if (arguments.length === 1) {
return getItem(this, key);
} else {
setItem(this, key, value);
return value;
}
});
};
}.call(this)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment