Last active
August 25, 2022 14:11
-
-
Save jinhoyim/010bb856dd0b20b2bd9ff9c1366a8f91 to your computer and use it in GitHub Desktop.
js delegation sample
This file contains 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Parcel Sandbox</title> | |
<meta charset="UTF-8" /> | |
<script defer src="src/index.js"><script> | |
</head> | |
<body> | |
<div id="app"> | |
<table id="table"> | |
<thead> | |
<tr> | |
<th>상품</th> | |
<th>단가</th> | |
<th>수량</th> | |
<th>금액</th> | |
</tr> | |
</thead> | |
<tbody></tbody> | |
</table> | |
</div> | |
</body> | |
</html> |
This file contains 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
(function () { | |
let data = [ | |
{ | |
name: 'Product1', | |
price: 10000, | |
qty: 2, | |
}, | |
{ | |
name: 'Product2', | |
price: 5000, | |
qty: 3, | |
}, | |
]; | |
const tbody = document.getElementById('table').querySelector('tbody'); | |
tbody.addEventListener('change', function (event) { | |
const { nodeName, classList, value } = event.target; | |
if (nodeName !== 'INPUT' || !classList.contains('qty')) { | |
return; | |
} | |
updateQty(event.target.closest('tr').dataset.index, parseInt(value, 10)); | |
render(data); | |
}); | |
function updateQty(dataIndex, qty) { | |
data[dataIndex] = { ...data[dataIndex], qty: qty }; | |
} | |
function render(data) { | |
let newNodeList = []; | |
newNodeList = data.map((i, index) => { | |
const tr = document.createElement('tr'); | |
tr.dataset.index = index; | |
tr.innerHTML = `<td>${i.name}</td> | |
<td>${i.price}</td> | |
<td><input type="text" class="qty" value="${i.qty}" /></td> | |
<td>${i.price * i.qty}</td>`; | |
return tr; | |
}); | |
tbody.replaceChildren(...newNodeList); | |
} | |
render(data); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment