Published
Edited
May 20, 2020
1 fork
1 star
Insert cell
Insert cell
doc = html`
<div>
<select name="cars">
<option value="sum">총합</option>
<option value="avg">평균</option>
<option value="dev">표준편차</option>
</select>
<output>0</output>
<div><button type="button" id="add">+</button></div>
</div>
`
Insert cell
// cloneNode로 이 셀을 복제해 사용하라
cell0 = html`<div class="cell"><button type="button">x</button><input type="number" value="0"></div>`
Insert cell
doc.querySelector("#add").addEventListener("click", addCell) // + 버튼에 이벤트 핸들러 등록
Insert cell
doc.addEventListener("change", calc) // select, input 내용이 변경되었을 때 실행할 이벤트 핸들러 등록
Insert cell
calc = () => { // 총합/평균/표준편차 계산해서 output에 내용 갱신
const output = doc.querySelector("output")
const vs = Array.from( doc.querySelectorAll(".cell input") ).map( i => Number(i.value) )
const sum = vs.reduce((x,y)=>x+y, 0) // vs에 있는 값들의 총합
const avg = sum / vs.length
// 표준편차 = 각각의 평균과의 차이의 제곱들의 총합을 길이로 나눠 제곱근
const dev = Math.sqrt( vs.map(v => (v-avg)*(v-avg)).reduce((x,y)=>x+y, 0) / vs.length )
switch ( doc.querySelector("select").value ) {
case "sum": output.value = sum; break;
case "avg": output.value = avg; break;
case "dev": output.value = dev; break;
}

}
Insert cell
addCell = () => {
const cell = cell0.cloneNode(true)
cell.querySelector("button").addEventListener("click", delCell) // 새로 추가되는 x 버튼에 이벤트 핸들러 등록
doc.appendChild(cell)
calc() // +버튼은 기본적으로 change 이벤트는 발생시키지 않으나 우리가 설계한 논리에서는 변화된 값을 반영하고 싶다
}
Insert cell
delCell = e => {
e.target.parentNode.remove()
calc() // x버튼은 기본적으로 change 이벤트는 발생시키지 않으나 우리가 설계한 논리에서는 변화된 값을 반영하고 싶다
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more