Skip to content

Instantly share code, notes, and snippets.

@AmilKey
Forked from bortevik/gist:c9310ab768e9baa5335a
Last active August 30, 2015 08:05
Show Gist options
  • Save AmilKey/c442df6f5d7499a41bdb to your computer and use it in GitHub Desktop.
Save AmilKey/c442df6f5d7499a41bdb to your computer and use it in GitHub Desktop.
LocalStorage wraper
App.StorageService = Ember.Object.extend({
persistence: window.localStorage,
namespace: 'ember-storage-service',
init: function() {
var callback = this._handleStorageEvent.bind(this);
$(window).on('storage', callback);
},
unknownProperty: function(key) {
var namespacedKey = this._key(key);
var payload = this.get('persistence').getItem(namespacedKey);
return this._deserialize(payload);
},
setUnknownProperty: function(key, value) {
var namespacedKey = this._key(key);
var payload = this._serialize(value);
this.get('persistence').setItem(namespacedKey, payload);
this.notifyPropertyChange(key);
return true;
},
removeItem: function(key) {
this.get('persistence').removeItem(this._key(key));
},
_serialize: function(value) {
return JSON.stringify(value);
},
_deserialize: function(value) {
return JSON.parse(value);
},
_key: function(key) {
return "%@:%@".fmt(this.get('namespace'), key);
},
_handleStorageEvent: function(event) {
var storageEvent = event.originalEvent;
var storageKey = storageEvent.key;
var tokens = storageKey.split(':');
var namespace = tokens[0];
var key = tokens[1];
if (key && namespace === this.get('namespace')) {
this.notifyPropertyChange(key);
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment