要保持缓存页面的Bootbox回调,可以使用localStorage或sessionStorage来存储回调函数。以下是一个示例解决方案:
// 保存回调函数到localStorage
function saveCallbackToCache(callback) {
// 生成一个唯一的键名
const key = 'bootboxCallback_' + Date.now();
// 将回调函数转换为字符串并存储到localStorage
localStorage.setItem(key, callback.toString());
return key;
}
// 从localStorage获取并执行回调函数
function executeCallbackFromCache(key) {
// 从localStorage中获取回调函数的字符串表示
const callbackString = localStorage.getItem(key);
if (callbackString) {
// 将字符串转换为函数
const callback = eval('(' + callbackString + ')');
if (typeof callback === 'function') {
// 执行回调函数
callback();
}
// 从localStorage中移除回调函数
localStorage.removeItem(key);
}
}
// 示例使用Bootbox的确认对话框
bootbox.confirm("Are you sure?", function(result) {
if (result) {
// 点击确认后的回调函数
console.log("Confirmed!");
} else {
// 点击取消后的回调函数
console.log("Canceled!");
}
// 将回调函数保存到localStorage
const callbackKey = saveCallbackToCache(arguments[1]);
// 将回调函数的键名保存到缓存页面的某个地方
sessionStorage.setItem('bootboxCallbackKey', callbackKey);
});
// 在缓存页面加载时执行之前保存的回调函数
const callbackKey = sessionStorage.getItem('bootboxCallbackKey');
if (callbackKey) {
executeCallbackFromCache(callbackKey);
// 清除保存的回调函数的键名
sessionStorage.removeItem('bootboxCallbackKey');
}
这里的示例代码使用了localStorage来保存回调函数,可以根据实际需求使用sessionStorage或其他合适的方式进行存储。在确认对话框的回调函数内部,使用saveCallbackToCache
函数将回调函数保存到localStorage,并将生成的键名保存到sessionStorage。在缓存页面加载时,使用executeCallbackFromCache
函数从localStorage获取并执行保存的回调函数。