feat: example06 작성 완료

This commit is contained in:
junilHwang
2020-10-25 21:28:36 +09:00
parent f46540ff47
commit 949db9500e
9 changed files with 90 additions and 0 deletions

View File

@@ -5,6 +5,7 @@
<title>Simple Component 1</title>
</head>
<body>
<h1>Example #1</h1>
<div id="app"></div>
<script>
const $app = document.querySelector('#app');

View File

@@ -5,6 +5,7 @@
<title>Simple Component 2</title>
</head>
<body>
<h1>Example #2</h1>
<div id="app"></div>
<script>
class Component {

View File

@@ -5,6 +5,7 @@
<title>Simple Component 3</title>
</head>
<body>
<h1>Example #3</h1>
<div id="app"></div>
<script src="./src/app.js" type="module"></script>
</body>

View File

@@ -5,6 +5,7 @@
<title>Simple Component 4</title>
</head>
<body>
<h1>Example #4</h1>
<div id="app"></div>
<script src="./src/app.js" type="module"></script>
</body>

View File

@@ -5,6 +5,7 @@
<title>Simple Component 5</title>
</head>
<body>
<h1>Example #5</h1>
<div id="app"></div>
<script src="./src/app.js" type="module"></script>
</body>

12
example06/index.html Normal file
View File

@@ -0,0 +1,12 @@
<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Simple Component 6</title>
</head>
<body>
<h1>Example #6</h1>
<div id="app"></div>
<script src="./src/app.js" type="module"></script>
</body>
</html>

10
example06/src/app.js Normal file
View File

@@ -0,0 +1,10 @@
import Items from "./components/Items.js";
class App {
constructor() {
const $app = document.querySelector('#app');
new Items($app);
}
}
new App();

View File

@@ -0,0 +1,35 @@
import Component from "../core/Component.js";
export default class Items extends Component {
setup () {
this.$state = { items: ['item1', 'item2'] };
}
template () {
const { items } = this.$state;
return `
<ul>
${items.map((item, key) => `
<li>
${item}
<button class="deleteBtn" data-index="${key}">삭제</button>
</li>
`).join('')}
</ul>
<button class="addBtn">추가</button>
`
}
setEvent () {
this.addEvent('click', '.addBtn', ({ target }) => {
const { items } = this.$state;
this.setState({ items: [ ...items, `item${items.length + 1}` ] });
});
this.addEvent('click', '.deleteBtn', ({ target }) => {
const items = [ ...this.$state.items ];
items.splice(target.dataset.index, 1);
this.setState({ items });
});
}
}

View File

@@ -0,0 +1,28 @@
export default class Component {
$target;
$state;
constructor ($target) {
this.$target = $target;
this.setup();
this.setEvent();
this.render();
}
setup () {};
template () { return ''; }
render () {
this.$target.innerHTML = this.template();
}
setEvent () {}
setState (newState) {
this.$state = { ...this.$state, ...newState };
this.render();
}
addEvent (eventType, selector, callback) {
const children = [ ...this.$target.querySelectorAll(selector) ];
const isTarget = (target) => children.includes(target) || target.closest(selector);
this.$target.addEventListener(eventType, event => {
if (!isTarget(event.target)) return false;
callback(event);
})
}
}