Last active
November 2, 2019 00:34
-
-
Save catkins/51a2c1cc1549e068e344 to your computer and use it in GitHub Desktop.
EmberJS Local Storage wrapper
This file contains 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
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
Can i reuse your code? What licence is this under?