Last active
June 30, 2017 13:13
-
-
Save ciarancolgan/f71450bf6d82327baf1d64cd96f78a7a to your computer and use it in GitHub Desktop.
Adding a switch to Footable.js to allow the use of sessionStorage instead of localStorage to preserve state
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- HTML DATA ATTRIBUTES REQUIRED: | |
- In your footable html <table> tag, add the attributes: | |
... data-state="true" data-state-sessionstorage="true" data-state-sessionstorageexpiration="5" ... | |
- JS CHANGES TO FOOTABLE.JS REQUIRED: | |
1) In the State 'preinit' function, add: | |
// Determine whether to use localStorage for state preservation or sessionStorage. | |
self.isSessionStorage = F.is.defined(data.stateSessionstorage) && F.is.boolean(data.stateSessionstorage) | |
? data.stateSessionstorage | |
: false; | |
// If using sessionStorage, determine how long to retain values. Default is 10 minutes. | |
self.sessionStorageExpirationMinutes = F.is.defined(data.stateSessionstorageexpiration) && F.is.number(data.stateSessionstorageexpiration) | |
? data.stateSessionstorageexpiration | |
: 10; | |
2) Then the 'get' becomes: | |
get: function (key) { | |
if (this.isSessionStorage) { | |
// Parse the value, look for a timestamp | |
var storageObject = JSON.parse(sessionStorage.getItem(this.key + ':' + key)); | |
if (storageObject !== null && F.is.defined(storageObject) && storageObject.hasOwnProperty("timestamp")) { | |
var now = new Date(), expiration = new Date(storageObject.timestamp); | |
expiration.setMinutes(expiration.getMinutes() + this.sessionStorageExpirationMinutes); | |
// ditch the content if too old | |
if (now.getTime() > expiration.getTime()) { | |
storageObject = null; | |
this.remove(this.key + ':' + key); | |
} | |
} | |
return storageObject; | |
} else { | |
return JSON.parse(localStorage.getItem(this.key + ':' + key)); | |
} | |
}, | |
3) And the 'set becomes: | |
set: function (key, data) { | |
if (this.isSessionStorage) { | |
data["timestamp"] = new Date(); | |
sessionStorage.setItem(this.key + ':' + key, JSON.stringify(data)); | |
} else { | |
localStorage.setItem(this.key + ':' + key, JSON.stringify(data)); | |
} | |
}, | |
4) And the 'remove' becomes: | |
remove: function (key) { | |
if (this.isSessionStorage) { | |
sessionStorage.removeItem(this.key + ':' + key); | |
} else { | |
localStorage.removeItem(this.key + ':' + key); | |
} | |
}, |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment