Persistv2.6.0

Provide cache interface to handle persisted data among history navigation.
#bfcache #storage

Getting Started

Browser support

IE 9+, latest of Chrome/FF/Safari, iOS 7+ and Android 2.3+ (except 3.x)

Feature

  • Providing key-value storage interface.
  • Data is persistent only during back-forward navigation.
  • Refreshing browser erases the data.
  • Can create an instance for each UI component using key string.
  • Can use dot notation path.

Quick steps to use

Install

npm install --save @egjs/persist

or use CDN


<script src="//naver.github.io/egjs-persist/release/latest/dist/persist.min.js"></script>

Initialize

ES5

var persist = new eg.Persist("componentID");

ES6+

import Persist from "@egjs/persist";
const persist = new Persist("componentID");

Usage

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"] 

Demos

Persisted comments loaded with ajax

  1. Click “load comments” button and load more comments.
  2. Click link to the end page.
  3. Go back with browser back button on mobile phone.
  4. Check loaded comments are still there.
  5. Click refresh button on mobile phone.
  6. Check loaded comments are gone.

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);
}