In the front-end daily development work, we often encounter the problem of repeated code development, such as a page, left slide and other common functions. Our solution might be to write a little this time, copy a little next time, and rewrite a little more if that doesn’t solve the problem. If you don’t take reusable code and make it generic and configurable, it doesn’t help your skills. So set a flag here, in the future work encountered reusable code, to effectively extract out, make a small plug-in, tool.

Problems to be solved

In web front-end development, data storage is often used, and the more commonly used ones are sessionStorage, localStorage and cookie. The integrated storage proposed in this paper is also based on these three storage objects.

Good use of storage can realize data multi-page sharing, improve page rendering speed, cache data/reduce server pressure and other benefits. But these storage objects are not very convenient to use, according to the author’s experience, when using cookies, sometimes will use jS-cookie operation cookie plug-in, using sessionStorage, localStorage, but also worried that the browser does not support, resulting in page error crash, You have to verify frequently that the browser supports these stored objects.

Therefore, at least the following questions can be drawn:

  1. Using JS to store objects directly is not simple enough;
  2. If the code is not rigorous enough, the page is at risk of crashing;
  3. Lack of a common integration tool to provide calls;

How to solve the problem

When dealing with the above problems, the well-known front-end library jquery is a good example, which has many ideas to learn from, for example:

  1. Easy to use API;
  2. Batch manipulation of data by passing objects, DOM;
  3. Provide chain calls, effectively simplify code;
  4. You can verify that the browser supports new features and resolve compatibility issues.

Through the above ideas, the author has implemented a small tool, some examples are introduced below

Related parameters

/* sessionStorage = sessionStorage; /* sessionStorage = sessionStorage; /* sessionStorage = sessionStorage Optional setting failure after the callback method: get get the value set set value remove delete sessionStorage isSupport determine whether support localStorage/cookie setType modified type * /
var storage = new StorageUtil(type,{
	success:function(){
		console.log('It worked');
	},
	fail:function(){
		console.log('Failed'); }});Copy the code

Environmental testing

Note: In terms of compatibility, the tool does not degrade automatically and can do so in the callback function if necessary

new StorageUtil().isSupport();//sessionStorage
new StorageUtil('localStorage').isSupport();//localStorage
new StorageUtil('cookie').isSupport();//cookie
Copy the code

Add and delete

Setting cookies is slightly different, and the time is optional

//sessionStorage
var storage = new StorageUtil();

storage.set('sessionStoragekey'.1);
storage.get('sessionStoragekey');/ / 1
console.log(sessionStorage.sessionStoragekey)/ / 1

//localStorage
var storage = new StorageUtil('localStorage');

storage.set('localStoragekey'.1);
storage.get('localStoragekey');/ / 1
console.log(localStorage.localStoragekey)/ / 1

//cookie
var storage = new StorageUtil('cookie'),
	time = 5 * 60 * 60 * 1000; //5 hours, 2 hours by default

storage.set('cookiekey'.1,time);
console.log(storage.get('cookiekey'));/ / 1
Copy the code

Chain calls

Since get is a value operation, the chain operation can only be set or remove

//set/remove
console.log(new StorageUtil().set('key1'.1).set('key2'.2).remove('key1').get('key2'));/ / 2
Copy the code

Direct store object

There is no need to manually convert object data

//sessionStorage/localStorage/cookie
new StorageUtil().set('obj', {'test':1}).get('obj')//{test: 1}
new StorageUtil('localStorage').set('obj', {'test':1}).get('obj')//{test: 1}
new StorageUtil('cookie').set('obj', {'test':1}).get('obj')//{test: 1}
Copy the code

The batch operation

When batch setting cookies, the time parameter is moved one bit forward

//批量get
new StorageUtil().get('key1,key2');
/ / bulk set sessionStorage/localStorage
new StorageUtil().set({ke1:1.key2:2});
// Batch set cookie time Optional
var time = 5 * 60 * 60 * 1000;

new StorageUtil('cookie').set({ke1:1.key2:2},time);
/ / batch delete sessionStorage localStorage/cookie
new StorageUtil().remove('key1,key2');
Copy the code

The following will introduce some more flexible ways, in the process of development, THE author also felt that JS is a very flexible language, if used well, the code can be very interesting

Change the type

You can play with three stored objects in a single line of code

new StorageUtil().set('key1'.1).setType('localStorage').set('key2'.2).
	.setType('cookie').set('key3'.3)
Copy the code

Infinite chain

new StorageUtil().set('msg'.'You came by,').get('msg'.function(msg){
	console.log(msg);
}).setType('localStorage').set('msg'.'Thought there was nothing left,').get('msg'.function(msg){
	console.log(msg);
}).setType('cookie').set('msg'.'But in my heart there are thoughts,').get('msg'.function(msg){
	console.log(msg);
}).setType('sessionStorage').set('msg'.'If you remember,').get('msg'.function(msg){
	console.log(msg);
}).setType('localStorage').set('msg'.'That summer of cicadas,').get('msg'.function(msg){
	console.log(msg);
}).setType('cookie').set('msg'.'There's a you and there's an me. ').get('msg'.function(msg){
	console.log(msg);
})
Copy the code

Infinite chain + batch

new StorageUtil().set({key3:3.key4:4}).get('key3,key4'.function(key3,key4){
	console.log(key3,key4);
}).remove('key3,key4');
Copy the code


That’s all about the tool. If you found it helpful, please give this article a thumbs up

Github address: storage-util


Related articles in this series (updated simultaneously) :

  1. Reorganize the reusable code in the front-end work (I) : make an integrated storage plug-in
  2. Reorganize reusable codes in front-end work (2) : Expand Spark-MD5 to support network file MD5 calculation