Store.js
PUBLISHED
Overview
This article demonstrates the use of "Store.js", which is a third party JavaScript library to store data locally in the browser. Store.js solves several problems in DOM storage.The main problem DOM storage is that it stringifies every value that is saved, so the contents cannot be put into groups of values into an object. Also there is no way to add an event listener for localstorage. Below are the links for javascript libraries used in this web application. 1) https://raw.github.com/kantorv/store-js/master/source/store.js 2) https://raw.github.com/marcuswestin/store.js/master/store.js 3) https://raw.github.com/andris9/jStorage/master/jstorage.min.js This web application uses three JS libraries of store.js. Each one of them has different features to store, retrieve and delete data from local storage.
1) store.js
In this JS library data is stored in key-value pairs. store.js provides functionality to create store, set key-value, get value, add event listener to key, import and export contents of store using objects and delete contents from store. store.js groups values into something called a store. Multiple stores are separated from each other. The below code creates a new store.
Creating store
var storage = new Store("storage");
New store is created using "new" keyword. "storage" is the name of the new store and that is saved in a variable.
Setting Key-Value
New key-value pair can be set using set() method.
storage.set("vehicle","car");
store.js saves the values with the store's name as a prefix, e.g. the key "vehicle" becomes "store.settings.vehicle" in localStorage, with a value="car". The key should always be a string.
Setting Default Values
Create an object with default values and pass it as the second argument to the constructor. Defaults are saved in the instance variable "defaults".
var defaults = { "website": "google", "testing": false }; var newStore = new Store("newStore", defaults);
Values can be set and retrieved from this object. After changing the defaults, always reapply them by calling the method applyDefaults(). The use of defaults is that when a key having a default value is set with a new value and when tried to delete the key then the value of that key will be restored with the default value.
newStore.defaults.website = "yahoo"; newStore.applyDefaults();
From the above code the key "website" is set with default value "google" and later set with "yahoo". So, when "website" is removed, "yahoo" will be deleted and the value of key will be restored to "google" (which is default value).
Retrieveing Value
A value can be retrieved from local storage using method get() from store.js. If a value is not present in local storage, it will return undefined.
storage.get("vehicle");
Objects
The contents of a store can be used as an object to export and import the data from one store to another. There are two methods for it: toObject() and fromObject(). "toObject()" : Exports all values of a store in an object. "fromObject()" : Replaces the complete store with the values passed in as an object i.e everything in the store gets removed, and replaced with new values. If second parameter for merge is false (which is the default), then the complete store will be removed(except the defaults) and replaced with the new values. If second parameter for merge is true, then new values will be added but values with same keys will be replaced with new values.
var mylocalstore = storage.toObject(); localstore.fromObject(mylocalstore,"true");
In the above code, contents from "storage" is exported and imported to "localstore" store. So all the contents of storage are merged with contents of localstore.
Events
Store.js supports events by checking periodically for new values. The default period is 500ms. To add and remove listeners the methods used are addEvent() and removeEvent(). "fireEvent()" is used internally to fire events. Event Listener can be added for a specific value or all values ("*").
localstore.addEvent("vehicle", function (value, name, store) { console.log("Key name is : " + name); console.log("Store of color is : " + store); console.log("New value of color is : " + value); });
The above code adds an event listener to key value "vehicle" and the callback function is called when the value of color is changed or deleted. This function is passed with three arguments: the new value, the name(key) of the value and the name of the store.
localstore.removeEvent("vehicle", callback);
The above code removes an event listener and the callback must be a pointer to the previously added function of addEvent().
Delete Contents
Contents from the store can be deleted using remove() and clear(). "clear()" removes everything from localStorage. "remove()" will delete a particular value when it's key is specified and if the value has a default, then the value will fall back to the default.
localstore.remove("vehicle"); Store.clear();
Other than these two, "reset()" will remove all values of a store and restores the defaults.
2) storage.js
This library has almost similar functionalities as the previously explained library for creating the store, setting, retrieveing and deleting values from store. The below code will check whether the local storage is available or not
if(store.enabled) { console.log("localStorage is available"); } else { console.log("localStorage not available"); }
Get All Values
"getAll()" method will retrieve all the values present in the store and returns array of those values.
var all_items=store.getAll(); showArray(all_items); function showArray(all_items){ var values = ""; console.log("All values stored : ") for (var i = 0; i < all_items.length; i++){ values=all_items[i]; console.log(i+") "+values); } }
3) jstorage.min.js
This JS library also has similar functions to set and get values from store.
$.jStorage.set(key, value); $.jStorage.get(key);
"deleteKey()" is used to remove a key from the storage. key needs to be string otherwise an exception is thrown.
$.jStorage.deleteKey(key);
"setTTL(key, ttl)" is used to set expiration time for a particular key. Time will be in milliseconds.
$.jStorage.set("mykey", "keyvalue"); $.jStorage.setTTL("mykey", 3000);
The above code will set a key which expires in three seconds. "getTTL(key)" will return the remaining TTL (in milliseconds) for a key or 0 if not TTL has been set.
ttl = $.jStorage.getTTL("mykey");
"flush()" clears the cache.
$.jStorage.flush();
"index()" returns all the keys currently in use as an array.
var index = $.jStorage.index(); console.log(index);
"storageSize()" returns the size of the stored data in bytes.
$.jStorage.storageSize();
"currentBackend()" returns the storage engine currently in use or false if none.
$.jStorage.currentBackend();
"storageAvailable()" returns true if storage is available.
$.jStorage.storageAvailable();
"listenKeyChange(key, callback)" listens for updates for selected key.
$.jStorage.listenKeyChange("mykey", function(key, action){ console.log(key + " has been " + action); });
"stopListening(key, callback)" stops listening for key change. If callback is set, only the used callback will be cleared, otherwise all listeners will be dropped.
$.jStorage.stopListening("mykey");
The above code will cancel all listeners for "mykey" change.