Provide cache interface to handle persisted data among history navigation.
#bfcache #storage
IE 9+, latest of Chrome/FF/Safari, iOS 7+ and Android 2.3+ (except 3.x)
npm install --save @egjs/persist
<script src="//naver.github.io/egjs-persist/release/latest/dist/persist.min.js"></script>
var persist = new eg.Persist("componentID");
import Persist from "@egjs/persist";
const persist = new Persist("componentID");
import Persist from "@egjs/persist";
const persist = new Persist("componentID");
// Overwrite global object
var snapshotObject = {
list: [{name: "foo"}, {name: "bar"}]
index: 0
};
persist.set("", snapshotObject);
// Get global object
persist.get("");
/*
{
list: [{name: "foo"}, {name: "bar"}]
index: 0
}
*/
// Get with property name and index
persist.get("index");
// => 0
persist.get("list.0");
// => {name: "foo"}
persist.get("list.0.name");
// => "foo"
// Set with property name and index
persist.set("list.2", "foo");
/* => this
{
list: [{name: "foo"}, {name: "bar"}, "foo"]
index: 0
}
*/
// Chaining with set method
persist
.set("isActive", false)
.set("index", 2)
.get("list");
//=> [{name: "foo"}, {name: "bar"}, "foo"]
const persist = new eg.Persist("commentModule");
$(".loadCmtBtn").on("click", function() {
// Make change to the component. (append comments)
$.get("/api/123/nextcomment", function(commentHtml) {
$(".commentContainer").append(commentHtml);
// Save snapshot of the component when there is a change
var snapshot = $(".commentContainer").html();
persist.set("commentsHTML", snapshot);
});
});
// Restore state when initiate component
if(!persist.get("") === null) {
var commentsHTML = persist.get("commentsHTML");
$(".commentContainer").html(commentsHTML);
}