Created
November 2, 2016 07:15
-
-
Save DriftwoodJP/fb78f1076b3475ccb3603112348a663d to your computer and use it in GitHub Desktop.
a Web Storage example.
This file contains hidden or 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
'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