Skip to content

Instantly share code, notes, and snippets.

@catkins
Last active November 2, 2019 00:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save catkins/51a2c1cc1549e068e344 to your computer and use it in GitHub Desktop.
Save catkins/51a2c1cc1549e068e344 to your computer and use it in GitHub Desktop.
EmberJS Local Storage wrapper
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);
}
}
});
@Br3nda
Copy link

Br3nda commented May 5, 2015

Can i reuse your code? What licence is this under?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment