local-store.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import Ember from 'ember';
  2. export default Ember.Service.extend({
  3. _storage: window.localStorage,
  4. _prefix: '_misago_',
  5. _watchers: null,
  6. _initWatches: function() {
  7. this.set('_watchers', []);
  8. var self = this;
  9. window.addEventListener('storage', function(e) {
  10. self._handleStorageEvent(e);
  11. });
  12. }.on('init'),
  13. _handleStorageEvent: function(e) {
  14. Ember.$.each(this.get('_watchers'), function(i, watcher) {
  15. if (watcher.keyName === e.key) {
  16. watcher.callback(e.newValue);
  17. }
  18. });
  19. },
  20. prefixKey: function(keyName) {
  21. return this.get('_prefix') + keyName;
  22. },
  23. setItem: function(keyName, value) {
  24. this.get('_storage').setItem(this.prefixKey(keyName), JSON.stringify(value));
  25. },
  26. getItem: function(keyName) {
  27. var itemJson = this.get('_storage').getItem(this.prefixKey(keyName));
  28. if (itemJson) {
  29. return JSON.parse(itemJson);
  30. } else {
  31. return null;
  32. }
  33. },
  34. watchItem: function(keyName, callback) {
  35. this.get('_watchers').push({keyName: this.prefixKey(keyName), callback: callback});
  36. }
  37. });