1 2 3 Polymer('core-localstorage', { 4 5 /** 6 * Fired when a value is loaded from localStorage. 7 * @event core-localstorage-load 8 */ 9 10 /** 11 * The key to the data stored in localStorage. 12 * 13 * @attribute name 14 * @type string 15 * @default null 16 */ 17 name: '', 18 19 /** 20 * The data associated with the specified name. 21 * 22 * @attribute value 23 * @type object 24 * @default null 25 */ 26 value: null, 27 28 /** 29 * If true, the value is stored and retrieved without JSON processing. 30 * 31 * @attribute useRaw 32 * @type boolean 33 * @default false 34 */ 35 useRaw: false, 36 37 /** 38 * If true, auto save is disabled. 39 * 40 * @attribute autoSaveDisabled 41 * @type boolean 42 * @default false 43 */ 44 autoSaveDisabled: false, 45 46 attached: function() { 47 // wait for bindings are all setup 48 this.async('load'); 49 }, 50 51 valueChanged: function() { 52 if (this.loaded && !this.autoSaveDisabled) { 53 this.save(); 54 } 55 }, 56 57 load: function() { 58 var v = localStorage.getItem(this.name); 59 if (this.useRaw) { 60 this.value = v; 61 } else { 62 // localStorage has a flaw that makes it difficult to determine 63 // if a key actually exists or not (getItem returns null if the 64 // key doesn't exist, which is not distinguishable from a stored 65 // null value) 66 // however, if not `useRaw`, an (unparsed) null value unambiguously 67 // signals that there is no value in storage (a stored null value would 68 // be escaped, i.e. "null") 69 // in this case we save any non-null current (default) value 70 if (v === null) { 71 if (this.value !== null) { 72 this.save(); 73 } 74 } else { 75 try { 76 v = JSON.parse(v); 77 } catch(x) { 78 } 79 this.value = v; 80 } 81 } 82 this.loaded = true; 83 this.asyncFire('core-localstorage-load'); 84 }, 85 86 /** 87 * Saves the value to localStorage. 88 * 89 * @method save 90 */ 91 save: function() { 92 var v = this.useRaw ? this.value : JSON.stringify(this.value); 93 localStorage.setItem(this.name, v); 94 } 95 96 }); 97 98