1 /** 2 * Olives http://flams.github.com/olives 3 * The MIT License (MIT) 4 * Copyright (c) 2012-2014 Olivier Scherrer <pode.fr@gmail.com> - Olivier Wietrich <olivier.wietrich@gmail.com> 5 */ 6 "use strict"; 7 8 var Store = require("emily").Store, 9 Tools = require("emily").Tools; 10 11 /** 12 * @class 13 * LocalStore is an Emily's Store that can be synchronized with localStorage 14 * Synchronize the store, reload your page/browser and resynchronize it with the same value 15 * and it gets restored. 16 * Only valid JSON data will be stored 17 */ 18 function LocalStoreConstructor() { 19 20 /** 21 * The name of the property in which to store the data 22 * @private 23 */ 24 var _name = null, 25 26 /** 27 * The localStorage 28 * @private 29 */ 30 _localStorage = localStorage, 31 32 /** 33 * Saves the current values in localStorage 34 * @private 35 */ 36 setLocalStorage = function setLocalStorage() { 37 _localStorage.setItem(_name, this.toJSON()); 38 }; 39 40 /** 41 * Override default localStorage with a new one 42 * @param local$torage the new localStorage 43 * @returns {Boolean} true if success 44 * @private 45 */ 46 this.setLocalStorage = function setLocalStorage(local$torage) { 47 if (local$torage && local$torage.setItem instanceof Function) { 48 _localStorage = local$torage; 49 return true; 50 } else { 51 return false; 52 } 53 }; 54 55 /** 56 * Get the current localStorage 57 * @returns localStorage 58 * @private 59 */ 60 this.getLocalStorage = function getLocalStorage() { 61 return _localStorage; 62 }; 63 64 /** 65 * Synchronize the store with localStorage 66 * @param {String} name the name in which to save the data 67 * @returns {Boolean} true if the param is a string 68 */ 69 this.sync = function sync(name) { 70 var json; 71 72 if (typeof name == "string") { 73 _name = name; 74 json = JSON.parse(_localStorage.getItem(name)); 75 76 Tools.loop(json, function (value, idx) { 77 if (!this.has(idx)) { 78 this.set(idx, value); 79 } 80 }, this); 81 82 setLocalStorage.call(this); 83 84 // Watch for modifications to update localStorage 85 this.watch("added", setLocalStorage, this); 86 this.watch("updated", setLocalStorage, this); 87 this.watch("deleted", setLocalStorage, this); 88 return true; 89 } else { 90 return false; 91 } 92 }; 93 } 94 95 module.exports = function LocalStoreFactory(init) { 96 LocalStoreConstructor.prototype = new Store(init); 97 return new LocalStoreConstructor(); 98 };