<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
</body>
</html>
/*
Есть компонент для ведения заметок, редактирование по клику на текст.
Задача: отрефактировать код без использования сторонних библиотек.
Исправить баги, улучшить качество, maintainability, читабельность.
CSS писать не нужно.
Должен получится независимый компонент,
легко встраиваемый в любую вёрстку и не ломающий окружение.
Возможно в будущем захочется сохранять данные на сервер
и как-то ещё расширять возможности компонента.
Инструкция:
- Сохранить изначальный код задачи в Secret Gist на Гитхабе.
- Отдельной правкой внести ваши изменения, чтобы можно было посмотреть diff.
- В ответе прислать ссылку на Gist и на JS Bin.
Ориентировочное время на выполнение задания — 1 час.
*/
let storage = {
data: ['foo', 'bar', '', 'foobar'],
add: function(text) {
this.data.unshift(text);
this.save();
},
set: function(i, text) {
this.data[i] = text;
this.save();
},
remove: function(i) {
this.data.splice(i, 1);
this.save();
},
save: function() {
window.localStorage.setItem('__notes_storage', JSON.stringify(this.data));
},
load: function() {
this.data = JSON.parse(window.localStorage.getItem('__notes_storage'));
}
};
let notes;
function renderNotes() {
if (notes) {
notes.parentNode.removeChild(notes);
}
notes = document.createElement('div');
document.body.appendChild(notes);
storage.data.forEach(renderNote.bind(null, notes));
}
function addNote() {
storage.add('');
renderNotes();
}
function removeNote(i) {
storage.remove(i);
renderNotes();
}
function saveNote(i, e) {
storage.set(i, e.currentTarget.previousSibling.value);
renderNotes();
}
function renderNote(parent, text, i) {
var note = document.createElement('div');
parent.appendChild(note);
var editEl = document.createElement('div');
editEl.style.display = 'none';
note.appendChild(editEl);
var textEl = document.createElement('div');
var labelText = text;
if (labelText == '') {
labelText = '<span style="color: #999; font-style: italic;">[empty]</span>'
}
textEl.innerHTML = labelText;
textEl.addEventListener('click', function() {
textEl.style.display = 'none';
editEl.style.display = '';
});
note.appendChild(textEl);
var textareaEl = document.createElement('textarea');
textareaEl.value = text;
editEl.appendChild(textareaEl);
var saveEl = document.createElement('button');
saveEl.appendChild(document.createTextNode('Save'));
saveEl.addEventListener('click', saveNote.bind(null, i));
editEl.appendChild(saveEl);
var removeEl = document.createElement('button');
removeEl.appendChild(document.createTextNode('Remove'));
removeEl.addEventListener('click', removeNote.bind(null, i));
editEl.appendChild(removeEl);
}
function renderCreateButton() {
let createButtonEl = document.createElement('button');
createButtonEl.appendChild(document.createTextNode('Add Note'));
createButtonEl.addEventListener('click', addNote);
document.body.appendChild(createButtonEl);
}
renderCreateButton();
renderNotes();
Output
You can jump to the latest bin by adding /latest
to your URL
Keyboard Shortcuts
Shortcut | Action |
---|---|
ctrl + [num] | Toggle nth panel |
ctrl + 0 | Close focused panel |
ctrl + enter | Re-render output. If console visible: run JS in console |
Ctrl + l | Clear the console |
ctrl + / | Toggle comment on selected lines |
ctrl + ] | Indents selected lines |
ctrl + [ | Unindents selected lines |
tab | Code complete & Emmet expand |
ctrl + shift + L | Beautify code in active panel |
ctrl + s | Save & lock current Bin from further changes |
ctrl + shift + s | Open the share options |
ctrl + y | Archive Bin |
Complete list of JS Bin shortcuts |
JS Bin URLs
URL | Action |
---|---|
/ | Show the full rendered output. This content will update in real time as it's updated from the /edit url. |
/edit | Edit the current bin |
/watch | Follow a Code Casting session |
/embed | Create an embeddable version of the bin |
/latest | Load the very latest bin (/latest goes in place of the revision) |
/[username]/last | View the last edited bin for this user |
/[username]/last/edit | Edit the last edited bin for this user |
/[username]/last/watch | Follow the Code Casting session for the latest bin for this user |
/quiet | Remove analytics and edit button from rendered output |
.js | Load only the JavaScript for a bin |
.css | Load only the CSS for a bin |
Except for username prefixed urls, the url may start with http://jsbin.com/abc and the url fragments can be added to the url to view it differently. |