Skip to content

Storage Implementation Spec

rbackhouse edited this page Sep 4, 2011 · 5 revisions

Storage Implementation Spec

By default the lsjs loader use storage implementation that uses HTML5 localStorage API's. It is possible to override this by setting the storageImpl configuration property to an object that provides the following API:

interface Storage {
    boolean isSupported(); // Checks to see if implementation is supported in client
    void get(String key, Function handler, Function errorHandler); // Objects the object stored for the specified key
    void set(String key, Object value, Function handler, Function errorHandler); // Sets the provided key/object in storage
    void remove(String key, Function handler, Function errorHandler); // Removes the value stored with the specified key
};

Here is the default lsjs implementation that uses localStorage :

lsImpl = {
	isSupported: function() {
		try {
			return 'localStorage' in window && window['localStorage'] !== null;
		} catch (e) {
			return false;
		}
	},	
	remove: function(key, handler, errorHandler) {
		try {
			var value = JSON.parse(localStorage[key]);
			localStorage.removeItem(key);
			if (handler) {
				handler(value);
			}
		} catch(e) {
			if (errorHandler) {
				errorHandler(e);
			} else {
				console.log("Failed to remove value in local storage ["+key+"] : "+e);
			}
		}
	},
	get: function(key, handler, errorHandler) {
		try {
			var value = JSON.parse(localStorage[key]);
			handler(value);
		} catch(e) {
			if (errorHandler) {
				errorHandler(e);
			} else {
				console.log("Failed to get value in local storage ["+key+"] : "+e);
			}
		}
	},
	set: function(key, entry, handler, errorHandler) {
		try {
			localStorage[key] = JSON.stringify(entry);
			if (handler) {
				handler(true);
			}
		} catch (e) {
			if (errorHandler) {
				errorHandler(e);
			} else {
				console.log("Failed to set value in local storage ["+key+"] : "+e);
			}
		}
	}
};