JSFiddle - React, Tailwind, and code Playground
HTML
<div id='notesContainer'>
</div>
JavaScript
const noteClassName = 'note';
const noteContainerClassName = 'note_container';
const emptyText = '[empty]';
const myHeaders = new Headers();
const urlRoot = 'https://jsonplaceholder.typicode.com';
const myInit = {
method: 'PUT',
headers: myHeaders,
mode: 'cors',
cache: 'default'
};
class EventEmitter {
constructor(target) {
target.observers = {};
target.subscribe = this.subscribe;
target.trigger = this.trigger;
}
subscribe(name, fn) {
if (!this.observers.hasOwnProperty(name)) {
this.observers[name] = [];
}
this.observers[name].push(fn);
return this;
}
trigger(name, ...args) {
if (this.observers.hasOwnProperty(name)) {
this.observers[name].forEach((item) => item(...args))
}
return this;
}
}
class StorageNotes {
constructor(name, target) {
localStorage.clear();
new EventEmitter(this);
this.name = name;
this.data = (this.load()) ? this.load() : [''];
target.subscribe('addData', text => {
this.add(text);
target.trigger('dataUpdate', this.data);
});
target.subscribe('removeData', i => {
this.remove(i);
target.trigger('dataUpdate', this.data);
});
target.subscribe('setData', (i, value) => {
this.set(i, value);
target.trigger('dataUpdate', this.data);
});
target.trigger('dataUpdate', this.data);
}
add(text) {
this.data.unshift(text);
this.save();
}
set(i, text) {
this.data[i] = text;
this.save();
}
remove(i) {
this.data.splice(i, 1);
this.save();
}
save() {
const dataSerialize = JSON.stringify(this.data);
window.localStorage.setItem(`__notes_storage_${this.name}`, dataSerialize);
//send data on server
fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'PUT',
body: dataSerialize,
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then((data) => data.json()).
then((userData) =>...