piskel/js/utils/UserSettings.js

76 lines
2.1 KiB
JavaScript
Raw Normal View History

(function () {
var ns = $.namespace("pskl");
ns.UserSettings = {
2013-06-17 23:03:22 +04:00
SHOW_GRID : 'SHOW_GRID',
CANVAS_BACKGROUND : 'CANVAS_BACKGROUND',
KEY_TO_DEFAULT_VALUE_MAP_ : {
'SHOW_GRID' : false,
'CANVAS_BACKGROUND' : 'medium-canvas-background'
},
/**
* @private
*/
2013-06-17 23:03:22 +04:00
cache_ : {},
/**
* Static method to access a user defined settings value ot its default
* value if not defined yet.
*/
get : function (key) {
2013-06-19 03:51:53 +04:00
this.checkKeyValidity_(key);
if (!(key in this.cache_)) {
this.cache_[key] =
this.readFromLocalStorage_(key) || this.readFromDefaults_(key);
}
2013-06-19 03:51:53 +04:00
return this.cache_[key];
},
set : function (key, value) {
2013-06-19 03:51:53 +04:00
this.checkKeyValidity_(key);
this.cache_[key] = value;
2013-06-19 03:51:53 +04:00
this.writeToLocalStorage_(key, value);
$.publish(Events.USER_SETTINGS_CHANGED, [key, value]);
},
/**
* @private
*/
2013-06-19 03:51:53 +04:00
readFromLocalStorage_ : function(key) {
var value = window.localStorage[key];
2013-06-19 03:51:53 +04:00
if (typeof value != "undefined") {
value = JSON.parse(value);
}
return value;
},
/**
* @private
*/
2013-06-19 03:51:53 +04:00
writeToLocalStorage_ : function(key, value) {
// TODO(grosbouddha): Catch storage exception here.
window.localStorage[key] = JSON.stringify(value);
},
/**
* @private
*/
readFromDefaults_ : function (key) {
return this.KEY_TO_DEFAULT_VALUE_MAP_[key];
},
2013-06-17 23:03:22 +04:00
/**
* @private
*/
2013-06-19 03:51:53 +04:00
checkKeyValidity_ : function(key) {
if(!(key in this.KEY_TO_DEFAULT_VALUE_MAP_)) {
// TODO(grosbouddha): Define error catching strategy and throw exception from here.
console.log("UserSettings key <"+ key +"> not find in supported keys.");
}
}
};
})();