Skip to content

Instantly share code, notes, and snippets.

@DriftwoodJP
Created November 2, 2016 07:15
Show Gist options
  • Save DriftwoodJP/fb78f1076b3475ccb3603112348a663d to your computer and use it in GitHub Desktop.
Save DriftwoodJP/fb78f1076b3475ccb3603112348a663d to your computer and use it in GitHub Desktop.
a Web Storage example.
'use strict';
const MyStorage = function(app) {
this.app = app;
this.storage = localStorage;
this.data = JSON.parse(this.storage[this.app] || '{}');
};
MyStorage.prototype = {
getItem: function(key) {
return this.data[key];
},
setItem: function(key, value) {
this.data[key] = value;
return this.data[key];
},
removeItem: function(key) {
let obj = JSON.parse(this.storage[this.app]);
delete obj[key];
return obj;
},
save: function(obj) {
this.storage[this.app] = JSON.stringify(obj || this.data);
}
};
window.addEventListener('DOMContentLoaded', function() {
const storage = new MyStorage('SampleApp');
const memo = document.getElementById('memo');
const clear = document.getElementById('clear');
memo.value = storage.getItem('wsMemo') || '';
memo.addEventListener('keyup', function() {
storage.setItem('wsMemo', memo.value);
storage.save();
});
clear.addEventListener('click', function() {
memo.value = null;
storage.save(storage.removeItem('wsMemo'));
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment