Skip to content

Instantly share code, notes, and snippets.

@sandywu
Created November 27, 2013 06:18
Show Gist options
  • Save sandywu/7671430 to your computer and use it in GitHub Desktop.
Save sandywu/7671430 to your computer and use it in GitHub Desktop.
通用storage
/**
* 本地存储
* @author etai
*/
Ju.add("sys.simpleStorage", function(J) {
var simpleStorage = function() {
var oStorage,
inited = false,
EMPTY_FUNC = function() {},
_setItem = EMPTY_FUNC,
_getItem = EMPTY_FUNC,
_removeItem = EMPTY_FUNC;
return {
init: function() {
var doc = document,
ie = doc.all,
STR_UNDEFINED = 'undefined',
IE_STORE_NAME = 'IEDataStore'; // IE6,7下,保存数据的xml文件名
if (inited) {return;}
if (typeof localStorage !== STR_UNDEFINED) {
// for IE8, FF 3.6, Chrome 4.1+, Safari 4+, Opera 10.5
oStorage = localStorage;
} else if (typeof globalStorage !== STR_UNDEFINED) {
// for FF unsupport localStorage
oStorage = globalStorage[location.hostname];
} else if (ie) { // IE6, 7,使用userData
oStorage = doc.createElement('input');
oStorage.type = 'hidden';
doc.body.appendChild(oStorage);
oStorage.addBehavior('#default#userData');
}
_setItem = function(key, value) {
var func = EMPTY_FUNC;
if ('setItem' in oStorage) {
func = function(key, value) {
oStorage.setItem(key, value);
};
} else if (ie) {
func = function(key, value) {
/*
* 添加try...catch的原因是:某些用户的IE,可能将安全级别设置得过高,或当前站点被添加至"受限站点"中(会
* 禁用掉"安全"tab下的"持续使用用户数据"选项,从而导致userData无法使用,这里通过try...catch来避免此
* 情况下的JS报错,下同。
*/
try {
oStorage.setAttribute(key, value);
oStorage.save(IE_STORE_NAME);
} catch(e){}
};
}
return func;
}();
_getItem = function(key) {
var func = EMPTY_FUNC;
if ('getItem' in oStorage) {
func = function(key) {
return oStorage.getItem(key);
};
} else if (ie) {
func = function(key) {
try {
oStorage.load(IE_STORE_NAME);
return oStorage.getAttribute(key);
} catch(e){}
};
}
return func;
}();
_removeItem = function(key) {
var func = EMPTY_FUNC;
if ('removeItem' in oStorage) {
func = function(key) {
oStorage.removeItem(key);
};
} else if (ie) {
func = function(key) {
try {
oStorage.removeAttribute(key);
oStorage.save(IE_STORE_NAME);
} catch(e){}
};
}
return func;
}();
inited = true;
},
setItem: function(key, value) {
return _setItem(key, value);
},
getItem: function(key) {
return _getItem(key);
},
removeItem: function(key) {
return _removeItem(key);
}
};
}();
J.sys.simpleStorage = simpleStorage;
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment