0%

오늘 배운 것

모듈

모듈은 재사용을 하기 위한 목적으로 설계된다. 일정 기능하는 것들을 분류해서 보관하고 애플리케이션 개발에서 가져다 쓸 수 있다.

모듈은 결합도는 낮게 응집도는 높게한다. → 서로 상호 의존도는 낮추고 각각의 독립적인 기능을 수행하는 것이다.

Component Based Development(CBD) 각각 독립적인 컴포넌트로 구성하고 이를 조합하여 프로그램을 구성하는 것이다.

모듈은 기능을 기준으로 파일 단위로 분류한다. 만약 파일명을 짓기 모호하다면 응집도가 낮은 것이다.(여러 기능을 하는 파일)

파일을 쪼개서 사용한다고 모두 모듈은 아니다. 파일 단위의 스코프를 가져야 모듈로서의 자격이 있다.

파일 단위 스코프라는 것은 각각 모듈이 완전 독립적이라는 것이다. 그렇기 때문에 export import를 사용하여 서로의 스코프로 불러 재사용할 수 있다.

모듈은 서로를 불러들여 재사용하며 의존관계가 형성된다. 하지만 의존성은 낮을 수록 좋다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// lib.js
const foo = 1;
const bar = 10;

// default export
export default foo;

// named export
export { bar };

// app.js
import foo, { bar } from "./lib.js";

console.log(foo, bar);

import한 원시값은 const로 할당되며 바꿀 수 없다. 하지만 참조값은 참조값이기 때문에 바꿀 수 있지만 권장하지 않는다.

1
2
3
4
5
6
7
8
9
10
11
12
13
// cal.js
const add = (a, b) => a + b;
const minus = (a, b) => a - b;

export { add, minus };

//app.js
import { add, minus } from "./cal.js";

const res = add(1, 2); // 3
const res2 = minus(3, 2); // 1

console.log(res, res2);

Nyong’s GitHub

오늘 배운 것

프로미스

비동기 처리로 발생한은 콜백헬과 에러처리에 대한 어려움으로 ES6에서 프로미스가 등장하였다.

콜백을 사용한 GET 비동기 함수

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// GET 요청을 위한 비동기 함수
const get = (url, callback) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.send();

xhr.onload = () => {
if (xhr.status === 200) {
// 서버의 응답을 콜백 함수에 전달하면서 호출하여 응답에 대한 후속 처리를 한다.
callback(JSON.parse(xhr.response));
} else {
console.error(`${xhr.status} ${xhr.statusText}`);
}
};
};

const url = "https://jsonplaceholder.typicode.com";

// id가 1인 post의 userId를 취득
get(`${url}/posts/1`, ({ userId }) => {
console.log(userId); // 1
// post의 userId를 사용하여 user 정보를 취득
get(`${url}/users/${userId}`, (userInfo) => {
console.log(userInfo); // {id: 1, name: "Leanne Graham", username: "Bret",...}
});
});

프로미스와 후속처리 메서드를 사용한 GET 메서드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// GET 요청을 위한 비동기 함수
const get = (url, callback) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.send();

xhr.onload = () => {
if (xhr.status === 200) {
// 서버의 응답을 콜백 함수에 전달하면서 호출하여 응답에 대한 후속 처리를 한다.
resolve(JSON.parse(xhr.response));
} else {
reject(new Erro(xhr.status));
}
};
});
};

const url = 'https://jsonplaceholder.typicode.com';

// 후속처리 메서드 then도 결국 콜백을 사용하게 된다.
get(`${url}/posts/1`)
.then(({ userId }) => get(`${url}/users/${userId}`));
.then(console.log);

후속처리 메서드는 일의 순서 대로 작성하는 것이 가독성이 좋다.

프로미스는 프로미스 객체를 반환하기 때문에 return 값이 프로미스 객체라면 바로 반환이 가능하지만 아니라면 프로미스 객체를 생성하여 값을 설정하고 넘긴다.

위의 경우 console.log 메서드가 중간에서 후속처리를했었다면 명시적으로 반환값을 넘기지 않으면 프로미스에 undefined 값을 설정하고 반환한다.

1
2
3
4
5
6
get(`${url}/posts/1`)
.then((post) => {
console.log(post); // 1
return post;
})
.then(({ userId }) => get(`${url}/users/${userId}`));

Promise.all

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const requestData1 = () =>
new Promise((resolve) => setTimeout(() => resolve(1), 3000));
const requestData2 = () =>
new Promise((resolve) => setTimeout(() => resolve(2), 2000));
const requestData3 = () =>
new Promise((resolve) => setTimeout(() => resolve(3), 1000));

// 세 개의 비동기 처리를 순차적으로 처리
const res = [];
requestData1()
.then((data) => {
res.push(data);
return requestData2();
})
.then((data) => {
res.push(data);
return requestData3();
})
.then((data) => {
res.push(data);
console.log(res); // [1, 2, 3] ⇒ 약 6초 소요
})
.catch(console.error);

위는 직렬 처리로 총 6초가 소요된다. 위와 같은 후속처리 체이닝은 위에서 작성한 GET 메서드와 같은 순차적인 처리가 필요할 때 사용하며 순차적인 처리가 필요한 경우가 아니라면 병렬 처리한다.

1
2
3
4
5
6
7
8
9
10
const requestData1 = () =>
new Promise((resolve) => setTimeout(() => resolve(1), 3000));
const requestData2 = () =>
new Promise((resolve) => setTimeout(() => resolve(2), 2000));
const requestData3 = () =>
new Promise((resolve) => setTimeout(() => resolve(3), 1000));

Promise.all([requestData1(), requestData2(), requestData3()])
.then(console.log) // [ 1, 2, 3 ] ⇒ 약 3초 소요
.catch(console.error);

위는 병렬 처리로 동시에 시작하기 때문에 총 3초가 소요된다. 병렬 처리가 훨씬 효율적이기 때문에 Promise.all을 사용해야한다.

all 메서드는 프로미스 객체로 이루어진 배열(이터러블)객체에 담아서 사용한다. 결과값으로 배열에 각 프로미스 객체의 결과값인 프로미스 객체가 순서대로 담기기 때문에 then 메서드로 받아야한다.

all 메서드에서 하나라도 rejected될 경우 모두 error 처리된다.

1
2
3
4
5
6
7
8
9
10
const githubIds = ["jeresig", "ahejlsberg", "ungmo2"];

Promise.all(
githubIds.map((id) => promiseGet(`https://api.github.com/users/${id}`))
)
// [Promise, Promise, Promise] => Promise [userInfo, userInfo, userInfo]
.then((users) => users.map((user) => user.name))
// [userInfo, userInfo, userInfo] => Promise ['John Resig', 'Anders Hejlsberg', 'Ungmo Lee']
.then(console.log)
.catch(console.error);

all 메서드는 위와 같은 GET으로 여러 값을 받을 때 사용할 수 있다.

Promise.allSettled

1
2
3
4
5
6
7
8
9
10
11
12
Promise.allSettled([
new Promise((resolve) => setTimeout(() => resolve(1), 2000)),
new Promise((_, reject) =>
setTimeout(() => reject(new Error("Error!")), 1000)
),
]).then(console.log);
/*
[
{status: "fulfilled", value: 1},
{status: "rejected", reason: Error: Error! at <anonymous>:3:54}
]
*/

모든 Settled 상태(fulfilled, rejected)를 반환한다.

Nyong’s GitHub

오늘 배운 것

에러처리

1
2
3
4
5
6
7
8
9
10
11
console.log("[Start]");

try {
foo();
} catch (error) {
console.error("[에러 발생]", error);
// [에러 발생] ReferenceError: foo is not defined
}

// 발생한 에러에 적절한 대응을 하면 프로그램이 강제 종료되지 않는다.
console.log("[End]");

에러가 발생했을 경우 강제 종료가 되는 것이 아닌 catch문을 실행 후 계속 코드를 실행시킨다.

catch (error) 에서 error에는 에러 객체가 전달된다.

옵션으로 finally 를 사용할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
console.log("[Start]");

try {
// 실행할 코드(에러가 발생할 가능성이 있는 코드)
foo();
} catch (err) {
// try 코드 블록에서 에러가 발생하면 이 코드 블록의 코드가 실행된다.
// err에는 try 코드 블록에서 발생한 Error 객체가 전달된다.
console.error(err); // ReferenceError: foo is not defined
} finally {
// 에러 발생과 상관없이 반드시 한 번 실행된다.
console.log("finally");
}

// try...catch...finally 문으로 에러를 처리하면 프로그램이 강제 종료되지 않는다.
console.log("[End]");
1
2
3
4
5
6
7
8
9
10
11
console.log("[Start]");

try {
throw new Error("somthing wrong");
} catch (err) {
console.error(err); // Error: somthing wrong
} finally {
console.log("finally");
}

console.log("[End]");

try catch문과 throw문과 Error객체를 함께 사용할 수 있다.

에러객체는 이벤트 객체의 버블랑과 유사하게 caller 방향으로 전파된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
const foo = () => {
throw Error("foo is wrong");
};

const bar = () => {
foo();
};

try {
bar();
} catch (err) {
console.error(err); // Error: foo is wrong
}

throw된 에러를 catch하지 않으면 강제 종료된다.

콜백 방식의 비동기 처리는 콜백 함수에 caller가 없기 때문에 에러 처리가 힘들다.

1
2
3
4
5
6
7
8
try {
setTimeout(() => {
throw new Error("Error!");
}, 1000);
} catch (e) {
// 에러를 캐치하지 못한다
console.error("캐치한 에러", e);
}

이미 setTimeout의 콜백함수가 테스크 큐에서 디큐되어 콜스택에서 실행될 때는 setTimeout 함수는 콜스택에 없기 때문에 콜백함수의 caller가 콜스택 내부에 없다. 이러한 이유로 비동기 함수에서 에러처리는 에러가 났을 때 실행할 콜백함수를 인수로 줬었다.

Promise

비동기 함수는 로직 안에 비동기로 동작하는 코드가 있다면 그 함수는 비동기 함수이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>

<body>
<button>click</button>
<script>
document.onclick = () => {
console.log("click me!");
return "click me";
};
</script>
</body>
</html>

이벤트 핸들러는 비동기로 동작하기 때문에 return 값이 의미가 없다.

이러한 이유 때문에 비동기 함수는 콜백함수를 이용하여 값을 전달 받았다. 하지만 콜백 함수를 이용하면 콜백헬 또는 에러 처리에 대한 어려움 등이 있다. 이와 같은 이유로 프로미스가 등장했다.

프로미스의 생성

1
2
3
4
5
6
7
8
9
// 프로미스 생성
const promise = new Promise((resolve, reject) => {
// Promise 함수의 콜백 함수 내부에서 비동기 처리를 수행한다.
if (/* 비동기 처리 성공 */) {
resolve('result');
} else { /* 비동기 처리 실패 */
reject('failure reason');
}
});

resolve의 인수값으로는 성공했을 시의 처리 reject의 인수값으로는 실패했을 시의 처리값을 인수로 준다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const get = (url) => {
const xhr = new XMLHttpRequest();

xhr.open("GET", url);
// xhr.setRequestHeader('content-type', 'application/json');
xhr.send();

xhr.onload = () => {
if (xhr.status === 200 || xhr.status === 201) {
console.log(JSON.parse(xhr.response));
} else {
console.error(xhr.status);
}
};
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const get = (url) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();

xhr.open("GET", url);
xhr.send();

xhr.onload = () => {
if (xhr.status === 200 || xhr.status === 201) {
// success
resolve(JSON.parse(xhr.response));
} else {
// failure
reject(xhr.status);
}
};
});
};

get("https://jsonplaceholder.typicode.com/todos/1")
.then(console.log)
.catch(console.error);

pending 상태인 프로미스에서 resolve를 호출하면 fulfilled 상태가 되고 reject를 호출하면 reject 상태가 된다.

Nyong’s GitHub

오늘 배운 것

REST API

JSON server로 로컬호스트와 연결하여 사용한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// 정보 은닉
const ajax = (() => {
const req = (method, url, successCallback, failureCallback, payload) => {
const xhr = new XMLHttpRequest();

xhr.open(method, url);
xhr.setRequestHeader("content-type", "application/json");
xhr.send(JSON.stringify(payload));

xhr.onload = () => {
if (xhr.status === 200 || xhr.status === 201) {
successCallback(JSON.parse(xhr.response));
} else {
failureCallback(xhr.status);
}
};
};

return {
get(url, successCallback, failureCallback) {
req("GET", url, successCallback, failureCallback);
},
post(url, payload, successCallback, failureCallback) {
req("POST", url, successCallback, failureCallback, payload);
},
patch(url, payload, successCallback, failureCallback) {
req("PATCH", url, successCallback, failureCallback, payload);
},
delete(url, successCallback, failureCallback) {
req("DELETE", url, successCallback, failureCallback);
},
};
})();

ajax.get("/todos", console.log, console.error);
ajax.post(
"/todos",
{ id: 6, content: "react", completed: false },
console.log,
console.error
);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// 객체 활용
const ajax = {
load(xhr) {
xhr.onload = () => {
if (xhr.status === 200 || xhr.status === 201) {
console.log(JSON.parse(xhr.response));
} else {
console.error(xhr.status);
}
};
},

get(url) {
const xhr = new XMLHttpRequest();

xhr.open("GET", url);
// xhr.setRequestHeader('content-type', 'application/json');
xhr.send();
this.load(xhr);
},

post(url, payload) {
const xhr = new XMLHttpRequest();

xhr.open("POST", url);
xhr.setRequestHeader("content-type", "application/json");
xhr.send(JSON.stringify(payload));

this.load(xhr);
},

patch(url, payload) {
const xhr = new XMLHttpRequest();

xhr.open("PATCH", url);
xhr.setRequestHeader("content-type", "application/json");
xhr.send(JSON.stringify(payload));

this.load(xhr);
},

remove(url) {
const xhr = new XMLHttpRequest();

xhr.open("DELETE", url);
// xhr.setRequestHeader('content-type', 'application/json');
xhr.send();

this.load(xhr);
},
};

Express

Express는 Node.js에서 사용하는 웹 애플리케이션 프래임워크다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
const express = require("express");
const cors = require("cors");

let todos = [
{ id: 3, content: "Javascript", completed: false },
{ id: 2, content: "CSS", completed: false },
{ id: 1, content: "HTML", completed: false },
];

const app = express();

app.use(cors());
app.use(express.static("public"));
app.use(express.json());

app.get("/todos", (req, res) => {
res.send(todos);
});

app.get("/todos/:id", (req, res) => {
const id = +req.params.id;

if (todos.map((todo) => todo.id).includes(id)) {
res.send(todos.filter((todo) => todo.id === +req.params.id));
} else {
res.send({
error: true,
reason: `id ${req.body.id}는 존재하지 않는 id입니다.`,
});
}
});

app.post("/todos", (req, res) => {
if (!todos.map((todo) => todo.id).includes(req.body.id)) {
todos = [req.body, ...todos];
res.send(todos);
} else {
res.send({
error: true,
reason: `id ${req.body.id}는 이미 존재하는 id입니다.`,
});
}
});

app.patch("/todos/:id", (req, res) => {
const id = +req.params.id;
const completed = req.body;

if (
todos.map((todo) => todo.id).includes(id) &&
typeof completed.completed === "boolean"
) {
todos = todos.map((todo) =>
todo.id === +id
? {
...todo,
...completed,
}
: todo
);
res.send(todos);
} else {
res.send({
error: true,
reason: `id ${req.body.id}에 대한 잘못된 접근입니다.`,
});
}
});

app.patch("/todos", (req, res) => {
const completed = req.body;
todos = todos.map((todo) => ({
...todo,
...completed,
}));
res.send(todos);
});

app.delete("/todos/completed", (req, res) => {
if (!todos.filter((todo) => todo.completed).length) {
res.send({
error: true,
reason: "완료된 요소가 없음.",
});
} else {
todos = todos.filter((todo) => !todo.completed);
res.send(todos);
}
});

app.delete("/todos/:id", (req, res) => {
const id = +req.params.id;

if (todos.map((todo) => todo.id).includes(id)) {
todos = todos.filter((todo) => todo.id !== +id);
res.send(todos);
} else {
res.send({
error: true,
reason: `id ${req.body.id}는 존재하지 않는 id입니다.`,
});
}
});

app.listen("7000", () => {
console.log("Server is listening on http://localhost:7000");
});

JSON에서는 사용하지 못하는 app이 제공하는 다양한 메서드를 사용할 수 있다.

Nyong’s GitHub

오늘 배운 것

Ajax

과거 전통적인 웹페이지는 서버에서 완전한 HTML 파일을 보내주면 다시 랜더링을 진행한다.

현재는 웹 어플리케이션에서 header, footer 등 바뀌지 않는 부분은 새로 랜더링하지 않는 방식을 Ajax를 통해서 구현하였다. 웹 페이지는 아직 전통적인 방식을 사용 중이다.

Json

서버통신을 위한 데이터 포멧이다.

REST API

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
const get = (url) => {
const xhr = new XMLHttpRequest();

xhr.open("GET", url);
// xhr.setRequestHeader('content-type', 'application/json');
xhr.send();

xhr.onload = () => {
if (xhr.status === 200 || xhr.status === 201) {
console.log(JSON.parse(xhr.response));
} else {
console.error(xhr.status);
}
};
};

const post = (url, payload) => {
const xhr = new XMLHttpRequest();

xhr.open("POST", url);
xhr.setRequestHeader("content-type", "application/json");
xhr.send(JSON.stringify(payload));

xhr.onload = () => {
if (xhr.status === 200 || xhr.status === 201) {
console.log(JSON.parse(xhr.response));
} else {
console.error(xhr.status);
}
};
};

const patch = (url, payload) => {
const xhr = new XMLHttpRequest();

xhr.open("PATCH", url);
xhr.setRequestHeader("content-type", "application/json");
xhr.send(JSON.stringify(payload));

xhr.onload = () => {
if (xhr.status === 200 || xhr.status === 201) {
console.log(JSON.parse(xhr.response));
} else {
console.error(xhr.status);
}
};
};

const remove = (url) => {
const xhr = new XMLHttpRequest();

xhr.open("DELETE", url);
// xhr.setRequestHeader('content-type', 'application/json');
xhr.send();

xhr.onload = () => {
if (xhr.status === 200 || xhr.status === 201) {
console.log(JSON.parse(xhr.response));
} else {
console.error(xhr.status);
}
};
};

get("/todos/2");
post("/todos", { id: 4, content: "React", completed: false });
patch("/todos/4", { completed: true });
remove("/todos/4");

Nyong’s GitHub

오늘 배운 것

타이머

JS 엔진은 싱글 스레드이기 때문에 호출 스케쥴링은 브라우저의 역할이다.

setTimeout / clearTimeout

브라우저, NodeJs가 호출하는 호스트 객체이다.

setTimeout은 항상 timerId를 반환한다. 이 함수를 이용해서 다른 반환값을 받는 것은 불가능하기 때문에 콜백함수를 통한 행위를 위해 사용해야한다.

반환하는 timerId는 clearTimeout, clearInterval에 사용된다.

간단한 타이머

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>

<body>
<div class="display">0</div>
<button class="start">start</button>
<button class="stop">stop</button>
<button class="reset">reset</button>
<script>
let num = 0;
let timerId = null;

const $start = document.querySelector(".start");
const $stop = document.querySelector(".stop");
const $reset = document.querySelector(".reset");
const $display = document.querySelector(".display");

$start.onclick = () => {
if (timerId) return;
timerId = setInterval(() => {
num += 1;
$display.textContent = num;
}, 100);
};

$stop.onclick = () => {
clearInterval(timerId);
timerId = null;
};

$reset.onclick = () => {
if (timerId) clearInterval(timerId);
num = 0;
$display.textContent = 0;
timerId = null;
};
</script>
</body>
</html>

비동기 프로그래밍

싱글 스레드인 JS엔진은 콜 스택이 하나뿐이기 때문에 시간이 걸리는 테스크를 처리할 때는 동기 처리방식으로 동작하기 때문에 처리 중인 테스크가 종료될 때까지 블로킹이 발생한다.

위에서 기술한 타이머 함수는 비동기로 동작한다. 커피를 주문하고(비동기 처리되는 함수) 주문벨(프로미스)이 울리기 전까지 다른 행위를 하는 것과 비슷하다.

타이머 함수 외에도 이벤트핸들러 또한 태스크 큐를 통해 실행된다. 때문에 테스크 큐를 이벤트 큐라고도 부른다. 이외에도 자바스크립트에서 호출하는 것이 아닌 브라우저가 호출하는 모든 태스크는 태스크 큐를 통해서 콜 스택에 들어온다.

함수 코드 중에 비동기로 동작하는 부분이 있다면 비동기 함수이다.

Nyong’s GitHub

비동기 프로그래밍

동기 처리과 비동기 처리

자바스크립트 엔진은 한 번에 하나의 태스크만 실행할 수 있는 싱글 스레드(single thread) 방식으로 동작한다. 싱글 스레드 방식은 한 번에 하나의 태스크만 실행할 수 있기 때문에 처리에 시간이 걸리는 태스크를 실행하는 경우 블로킹(blocking, 작업 중단)이 발생한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// sleep 함수는 일정 시간(delay)이 경과한 이후에 콜백 함수(func)를 호출한다.
function sleep(func, delay) {
// Date.now()는 현재 시간을 숫자(ms)로 반환한다.("30.2.1. Date.now" 참고)
const delayUntil = Date.now() + delay;

// 현재 시간(Date.now())에 delay를 더한 delayUntil이 현재 시간보다 작으면 계속 반복한다.
while (Date.now() < delayUntil);
// 일정 시간(delay)이 경과한 이후에 콜백 함수(func)를 호출한다.
func();
}

function foo() {
console.log("foo");
}

function bar() {
console.log("bar");
}

// sleep 함수는 3초 이상 실행된다..
sleep(foo, 3 * 1000);
// bar 함수는 sleep 함수의 실행이 종료된 이후에 호출되므로 3초 이상 블로킹된다.
bar();
// (3초 경과 후) foo 호출 -> bar 호출

이처럼 현재 실행 중인 태스크가 종료할 때까지 다음에 실행될 태스크가 대기하는 방식을 동기(synchronous) 처리라고 한다. 동기 처리 방식은 태스크를 순서대로 하나씩 처리하므로 실행 순서가 보장된다는 장점이 있지만, 앞선 태스크가 종료할 때까지 이후 태스크들이 블로킹되는 단점이 있다.

setTimeout 함수는 이후의 태스크를 블로킹하지 않고 곧바로 실행한다. 이처럼 현재 실행 중인 태스크가 종료되지 않은 상태라 해도 다음 태스크를 곧바로 실행하는 방식을 비동기(asynchronous) 처리라고 한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
function foo() {
console.log("foo");
}

function bar() {
console.log("bar");
}

// 타이머 함수 setTimeout은 일정 시간이 경과한 이후에 콜백 함수 foo를 호출한다.
// 타이머 함수 setTimeout은 bar 함수를 블로킹하지 않는다.
setTimeout(foo, 3 * 1000);
bar();
// bar 호출 -> (3초 경과 후) foo 호출

현재 실행 중인 태스크가 종료되지 않은 상태라 해도 다음 태스크를 곧바로 실행하므로 블로킹이 발생하지 않는다는 장점이 있지만 태스크의 실행 순서가 보장되지 않는 단점이 있다.

이벤트 루프와 태스크 큐

자바스크립트의 동시성(concurrency)을 지원하는 것이 바로 이벤트 루프(event loop)다.

구글의 V8 자바스크립트 엔진을 비롯한 대부분의 자바스크립트 엔진은 크게 2개의 영역으로 구분할 수 있다.

  • 콜 스택(call stack)
    소스코드(전역 코드나 함수 코드 등) 평가 과정에서 생성된 실행 컨텍스트가 추가되고 제거되는 스택 자료구조인 실행 컨텍스트 스택이 바로 콜 스택이다.
    함수를 호출하면 함수 실행 컨텍스트가 순차적으로 콜 스택에 푸시되어 순차적으로 실행된다. 자바스크립트 엔진은 단 하나의 콜 스택을 사용하기 때문에 최상위 실행 컨텍스트(실행 중인 실행 컨텍스트)가 종료되어 콜 스택에서 제거되기 전까지는 다른 어떤 태스크도 실행되지 않는다.
  • 힙(heap)
    힙은 객체가 저장되는 메모리 공간이다. 콜 스택의 요소인 실행 컨텍스트는 힙에 저장된 객체를 참조한다.
    메모리에 값을 저장하려면 먼저 값을 저장할 메모리 공간의 크기를 결정해야 한다. 객체는 원시값과는 달리 크기가 정해져 있지 않으므로 할당해야 할 메모리 공간의 크기를 런타임에 결정(동적 할당)해야 한다. 따라서 객체가 저장되는 메모리 공간인 힙은 구조화되어 있지 않다는 특징이 있다.

콜 스택과 힙으로 구성되어 있는 자바스크립트 엔진은 단순히 태스크가 요청되면 콜 스택을 통해 요청된 작업을 순차적으로 실행할 뿐이다. 비동기 처리에서 소스코드의 평가와 실행을 제외한 모든 처리는 자바스크립트 엔진을 구동하는 환경인 브라우저 또는 Node.js가 담당한다. 예를 들어, 비동기 방식으로 동작하는 setTimeout의 콜백 함수의 평가와 실행은 자바스크립트 엔진이 담당하지만 호출 스케줄링을 위한 타이머 설정과 콜백 함수의 등록은 브라우저 또는 Node.js가 담당한다. 이를 위해 브라우저 환경은 태스크 큐와 이벤트 루프를 제공한다.

  • 태스크 큐(task queue/event queue/callback queue)
    setTimeout이나 setInterval과 같은 비동기 함수의 콜백 함수 또는 이벤트 핸들러가 일시적으로 보관되는 영역이다. 태스크 큐와는 별도로 프로미스의 후속 처리 메서드의 콜백 함수가 일시적으로 보관되는 마이크로태스크 큐도 존재한다. 이에 대해서는 마이크로태스크 큐에서 살펴보자.
  • 이벤트 루프(event loop)
    이벤트 루프는 콜 스택에 현재 실행 중인 실행 컨텍스트가 있는지, 그리고 태스크 큐에 대기 중인 함수(콜백 함수, 이벤트 핸들러 등)가 있는지 반복해서 확인한다. 만약 콜 스택이 비어 있고 태스크 큐에 대기 중인 함수가 있다면 이벤트 루프는 순차적(FIFO, First In First Out)으로 태스크 큐에 대기 중인 함수를 콜 스택으로 이동시킨다. 이때 콜 스택으로 이동한 함수는 실행된다. 즉, 태스크 큐에 일시 보관된 함수들은 비동기 처리 방식으로 동작한다.
1
2
3
4
5
6
7
8
9
10
function foo() {
console.log("foo");
}

function bar() {
console.log("bar");
}

setTimeout(foo, 0); // 0초(실제는 4ms) 후에 foo 함수가 호출된다.
bar();
  1. 전역 코드가 평가되어 전역 실행 컨텍스트가 생성되고 콜 스택에 푸시된다.

  2. 전역 코드가 실행되기 시작하여 setTimeout 함수가 호출된다. 이때 setTimeout 함수의 함수 실행 컨텍스트가 생성되고 콜 스택에 푸시되어 현재 실행 중인 실행 컨텍스트가 된다. 브라우저의 Web API(호스트 객체)인 타이머 함수도 함수이므로 함수 실행 컨텍스트를 생성한다.

  3. setTimeout 함수가 실행되면 콜백 함수를 호출 스케줄링하고 종료되어 콜 스택에서 팝된다. 이때 호출 스케줄링, 즉 타이머 설정과 타이머가 만료되면 콜백 함수를 태스크 큐에 푸시하는 것은 브라우저의 역할이다.

  4. 브라우저가 수행하는 4.1과 자바스크립트 엔진이 수행하는 4.2는 병행 처리된다.

  5. 브라우저는 타이머를 설정하고 타이머의 만료를 기다린다. 이후 타이머가 만료되면 콜백 함수 foo가 태스크 큐에 푸시된다. 위 예제의 경우 지연 시간(delay)이 0이지만 지연 시간이 4ms 이하인 경우 최소 지연 시간 4ms가 지정된다. 따라서 4ms 후에 콜백 함수 foo가 태스크 큐에 푸시되어 대기하게 된다. 이 처리 또한 자바스크립트 엔진이 아니라 브라우저가 수행한다. 이처럼 setTimeout 함수로 호출 스케줄링한 콜백 함수는 정확히 지연 시간 후에 호출된다는 보장은 없다. 지연 시간 이후에 콜백 함수가 태스크 큐에 푸시되어 대기하게 되지만 콜 스택이 비어야 호출되므로 약간의 시간차가 발생할 수 있기 때문이다.

  6. bar 함수가 호출되어 bar 함수의 함수 실행 컨텍스트가 생성되고 콜 스택에 푸시되어 현재 실행 중인 실행 컨텍스트가 된다. 이후 bar 함수가 종료되어 콜 스택에서 팝된다. 이때 브라우저가 타이머를 설정한 후 4ms 가 경과했다면 foo 함수는 아직 태스크 큐에서 대기 중이다.

  7. 전역 코드 실행이 종료되고 전역 실행 컨텍스트가 콜 스택에서 팝된다. 이로서 콜 스택에는 아무런 실행 컨텍스트도 존재하지 않게 된다.

  8. 이벤트 루프에 의해 콜 스택이 비어 있음이 감지되고 태스크 큐에서 대기 중인 콜백 함수 foo가 이벤트 루프에 의해 콜 스택에 푸시된다. 다시 말해, 콜백 함수 foo의 함수 실행 컨텍스트가 생성되고 콜 스택에 푸시되어 현재 실행 중인 실행 컨텍스트가 된다. 이후 foo 함수가 종료되어 콜 스택에서 팝된다.

비동기 함수인 setTimeout의 콜백 함수는 태스크 큐에 푸시되어 대기하다가 콜 스택이 비게 되면, 다시 말해 전역 코드 및 명시적으로 호출된 함수가 모두 종료하면 비로소 콜 스택에 푸시되어 실행된다.

자바스크립트는 싱글 스레드 방식으로 동작한다. 이때 싱글 스레드로 동작하는 것은 브라우저가 아니라 브라우저에 내장된 자바스크립트 엔진이라는 것에 주의하기 바란다. 만약 모든 자바스크립트 코드가 자바스크립트 엔진에서 싱글 스레드 방식으로 동작한다면 자바스크립트는 비동기로 동작할 수 없다. 즉, 자바스크립트 엔진은 싱글 스레드로 동작하지만 브라우저는 멀티 스레드로 동작한다.

참고 도서: 모던 자바스크립트 Deep Dive

Nyong’s GitHub

오늘 배운 것

이벤트

DOMContentLoaded

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script>
// // window가 모두 로드되면 실행한다.
// window.onload = () => {
// document.querySelector('.foo').style.color = 'red';
// };

// DOM 생성이 완성되면 로드한다. (위 보다 빠르다.)
document.addEventListener("DOMContentLoaded", () => {
document.querySelector(".foo").style.color = "red";
});
</script>
</head>
<body>
<div class="foo">test</div>
</body>
</html>

TODO

웹사이트 방식

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
/* css로도 취소선 생성이 가능하다. */
.todos > li > input[type="checkbox"]:checked + span {
text-decoration: line-through;
}
</style>
</head>

<body>
<form>
<input class="input-todo" type="text" placeholder="enter todo!" />
<!-- 버튼 타입을 버튼으로 지정하지 않으면 submit이 기본값 -->
<button class="add">Add</button>
</form>

<ul class="todos"></ul>

<script>
const $form = document.querySelector("form");
const $inputTodo = document.querySelector(".input-todo");
// const $add = document.querySelector('.add'); // submit 버튼을 add로 대체
const $todos = document.querySelector(".todos");

const addTodo = () => {
const { value } = $inputTodo;
if (!value) return;

// $todos.innerHTML += `<li>${value}</li>`;
const $li = document.createElement("li");
const $checkbox = document.createElement("input");
const $span = document.createElement("span");
const $remove = document.createElement("button");

$checkbox.setAttribute("type", "checkbox");

$span.textContent = value;
$remove.classList.add("remove");
$remove.textContent = "X";

$li.appendChild($checkbox);
$li.appendChild($span);
$li.appendChild($remove);
$todos.appendChild($li);

$inputTodo.value = "";
$inputTodo.focus();
};

// $add.onclick = addTodo;

// $inputTodo.onkeyup = e => {
// if (e.key !== 'Enter') return;
// addTodo();
// };

$form.onsubmit = (e) => {
e.preventDefault();
addTodo();
};

// 부모요소에게 이벤트를 위임하였다. (remove list)
$todos.onclick = (e) => {
if (!e.target.classList.contains("remove")) return;
e.target.parentNode.remove();
};

/*
// check 시 취소선
$todos.addEventListener('click', e => {
e.target.checked ? e.target.nextSibling.style.textDecoration = 'line-through':e.target.nextSibling.style.textDecoration = 'none';
});

// click은 쓸모없는 마우스 좌표를 가져온다.
// css로 할 수도 있다.
$todos.onchange = ({ target }) => {
target.nextSibling.style.textDecoration = target.checked ? 'line-through' : 'none';
};
*/
</script>
</body>
</html>

TODO MVC 패턴(미완성)

서버로 데이터를 동기화할 때는 배열 자료구조를 통한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>

<body>
<form>
<input type="text" class="input-todo" placeholder="enter todo!" />
<button class="add">등록</button>
</form>

<ul class="todos">
<!-- <li id="1">
<input type="checkbox" checked>
<span>HTML</span>
<button class="remove">X</button>
</li> -->
</ul>
<script>
let todos = [];

const $todos = document.querySelector(".todos");
const $inputTodo = document.querySelector(".todos");

const render = () => {
$todos.innerHTML = todos
.map(
({ id, content, completed }) => `<li id="${id}">
<input type="checkbox" ${completed ? "checked" : ""}>
<span>${content}</span>
<button class="remove">X</button>
</li>`
)
.join("");
};

const fetchTodos = () => {
// TODO: 서버로부터 todos 데이터를 취득한다.(잠정 처리)
todos = [
{ id: 1, content: "HTML", completed: true },
{ id: 2, content: "CSS", completed: true },
{ id: 3, content: "Javascript", completed: false },
];

todos = [...todos].sort((todo1, todo2) => todo2.id - todo1.id);
render();
};

const addTodo = (() => {
const generateId = () => Math.max(...todos.map((todo) => todo.id)) + 1;

return (content) => {
todos = [
{
id: generateId(),
content,
completed: false,
},
...todos,
];
render();
};
})();

const removeTodo = (id) => {
todos = todos.filter((todo) => todo.id !== id);
render();
};

document.addEventListener("DOMContentLoaded", fetchTodos);

document.querySelector("form").onsubmit = (e) => {
e.preventDefault();
const content = $inputTodo.value;
if (!content) return;

addTodo(content);
$inputTodo.value = "";
$inputTodo.focus();
};

$todos.onclick = (e) => {
if (!e.target.matches(".todos > li > button.remove")) return;

removeTodo(+e.target.parentNode.id);
};
</script>
</body>
</html>

Nyong’s GitHub

타이머

setTimeout / clearTimeout

1
2
3
4
5
6
7
8
9
10
11
12
13
const timeoutId = setTimeout(func|code[, delay, param1, param2, ...]);

// 1초(1000ms) 후 타이머가 만료되면 콜백 함수가 호출된다.
// 이때 콜백 함수에 'Lee'가 인수로 전달된다.
setTimeout(name => console.log(`Hi! ${name}.`), 1000, 'Lee');

// 1초(1000ms) 후 타이머가 만료되면 콜백 함수가 호출된다.
// setTimeout 함수는 생성된 타이머를 식별할 수 있는 고유한 타이머 id를 반환한다.
const timerId = setTimeout(() => console.log('Hi!'), 1000);

// setTimeout 함수가 반환한 타이머 id를 clearTimeout 함수의 인수로 전달하여 타이머를 취소한다.
// 타이머가 취소되면 setTimeout 함수의 콜백 함수가 실행되지 않는다.
clearTimeout(timerId);

setInterval / clearInterval

1
2
3
4
5
6
7
8
9
10
11
12
setInterval(func|code[, delay, param1, param2, ...]);

let count = 1;

// 1초(1000ms) 후 타이머가 만료될 때마다 콜백 함수가 호출된다.
// setInterval 함수는 생성된 타이머를 식별할 수 있는 고유한 타이머 id를 반환한다.
const timeoutId = setInterval(() => {
console.log(count); // 1 2 3 4 5
// count가 5이면 setInterval 함수가 반환한 타이머 id를 clearInterval 함수의 인수로 전달하여
// 타이머를 취소한다. 타이머가 취소되면 setInterval 함수의 콜백 함수가 실행되지 않는다.
if (count++ === 5) clearInterval(timeoutId);
}, 1000);

디바운스와 스로틀

디바운스와 스로틀은 짧은 시간 간격으로 연속해서 발생하는 이벤트를 그룹화해서 과도한 이벤트 핸들러의 호출을 방지하는 프로그래밍 기법이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<!DOCTYPE html>
<html>
<body>
<button>click me</button>
<pre>일반 클릭 이벤트 카운터 <span class="normal-msg">0</span></pre>
<pre>디바운스 클릭 이벤트 카운터 <span class="debounce-msg">0</span></pre>
<pre>스로틀 클릭 이벤트 카운터 <span class="throttle-msg">0</span></pre>
<script>
const $button = document.querySelector("button");
const $normalMsg = document.querySelector(".normal-msg");
const $debounceMsg = document.querySelector(".debounce-msg");
const $throttleMsg = document.querySelector(".throttle-msg");

const debounce = (callback, delay) => {
let timerId;
return (event) => {
if (timerId) clearTimeout(timerId);
timerId = setTimeout(callback, delay, event);
};
};

const throttle = (callback, delay) => {
let timerId;
return (event) => {
if (timerId) return;
timerId = setTimeout(
() => {
callback(event);
timerId = null;
},
delay,
event
);
};
};

$button.addEventListener("click", () => {
$normalMsg.textContent = +$normalMsg.textContent + 1;
});

$button.addEventListener(
"click",
debounce(() => {
$debounceMsg.textContent = +$debounceMsg.textContent + 1;
}, 500)
);

$button.addEventListener(
"click",
throttle(() => {
$throttleMsg.textContent = +$throttleMsg.textContent + 1;
}, 500)
);
</script>
</body>
</html>

디바운스

디바운스(debounce)는 짧은 시간 간격으로 이벤트가 연속해서 발생하면 이벤트 핸들러를 호출하지 않다가 일정 시간이 경과한 이후에 이벤트 핸들러가 한 번만 호출되도록 한다. 즉, 디바운스는 짧은 시간 간격으로 발생하는 이벤트를 그룹화해서 마지막에 한 번만 이벤트 핸들러가 호출되도록 한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE html>
<html>
<body>
<input type="text" />
<div class="msg"></div>
<script>
const $input = document.querySelector("input");
const $msg = document.querySelector(".msg");

const debounce = (callback, delay) => {
let timerId;
// debounce 함수는 timerId를 기억하는 클로저를 반환한다.
return (event) => {
// delay가 경과하기 이전에 이벤트가 발생하면 이전 타이머를 취소하고 새로운 타이머를 재설정한다.
// 따라서 delay보다 짧은 간격으로 이벤트가 발생하면 callback은 호출되지 않는다.
if (timerId) clearTimeout(timerId);
timerId = setTimeout(callback, delay, event);
};
};

// debounce 함수가 반환하는 클로저가 이벤트 핸들러로 등록된다.
// 300ms보다 짧은 간격으로 input 이벤트가 발생하면 debounce 함수의 콜백 함수는
// 호출되지 않다가 300ms 동안 input 이벤트가 더 이상 발생하면 한 번만 호출된다.
$input.oninput = debounce((e) => {
$msg.textContent = e.target.value;
}, 300);
</script>
</body>
</html>

스로틀

스로틀(throttle)은 짧은 시간 간격으로 이벤트가 연속해서 발생하더라도 일정 시간 간격으로 이벤트 핸들러가 최대 한 번만 호출되도록 한다. 즉, 스로틀은 짧은 시간 간격으로 연속해서 발생하는 이벤트를 그룹화해서 일정 시간 단위로 이벤트 핸들러가 호출되도록 호출 주기를 만든다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<!DOCTYPE html>
<html>
<head>
<style>
.container {
width: 300px;
height: 300px;
background-color: rebeccapurple;
overflow: scroll;
}

.content {
width: 300px;
height: 1000vh;
}
</style>
</head>
<body>
<div class="container">
<div class="content"></div>
</div>
<div>
일반 이벤트 핸들러가 scroll 이벤트를 처리한 횟수:
<span class="normal-count">0</span>
</div>
<div>
스로틀 이벤트 핸들러가 scroll 이벤트를 처리한 횟수:
<span class="throttle-count">0</span>
</div>

<script>
const $container = document.querySelector(".container");
const $normalCount = document.querySelector(".normal-count");
const $throttleCount = document.querySelector(".throttle-count");

const throttle = (callback, delay) => {
let timerId;
// throttle 함수는 timerId를 기억하는 클로저를 반환한다.
return (event) => {
// delay가 경과하기 이전에 이벤트가 발생하면 아무것도 하지 않다가
// delay가 경과했을 때 이벤트가 발생하면 새로운 타이머를 재설정한다.
// 따라서 delay 간격으로 callback이 호출된다.
if (timerId) return;
timerId = setTimeout(
() => {
callback(event);
timerId = null;
},
delay,
event
);
};
};

let normalCount = 0;
$container.addEventListener("scroll", () => {
$normalCount.textContent = ++normalCount;
});

let throttleCount = 0;
// throttle 함수가 반환하는 클로저가 이벤트 핸들러로 등록된다.
$container.addEventListener(
"scroll",
throttle(() => {
$throttleCount.textContent = ++throttleCount;
}, 100)
);
</script>
</body>
</html>

참고 도서: 모던 자바스크립트 Deep Dive

Nyong’s GitHub

오늘 배운 것

DOM

data 어트리뷰트와 dataset 프로퍼티

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html>
<body>
<ul class="todos">
<li id="1" data-user-id="1">HTML</li>
<li id="2" data-user-id="2">CSS</li>
<li id="2" data-user-id="3">JS</li>
</ul>
<script>
document.querySelector(".todos > li").dataset.customerId = "0"; // 해당 어트리뷰트가 없으면 생성한다.
console.log(document.querySelector(".todos > li").dataset.userId); // 1
</script>
</body>
</html>

스타일

인라인 스타일 조작

1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE html>
<html>
<body>
<ul class="todos">
<li id="1">HTML</li>
<li id="2">CSS</li>
<li id="2">JS</li>
</ul>
<script>
document.querySelector(".todos > li").style.color = "red";
</script>
</body>
</html>

클래스 조작

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html>
<head>
<style>
.red {
color: red;
}
.big {
font-size: 10em;
}
</style>
</head>
<body>
<ul class="todos">
<li id="1">HTML</li>
<li id="2">CSS</li>
<li id="2">JS</li>
</ul>
<script>
document.querySelector(".todos > li").className = "red big";
</script>
</body>
</html>

className은 문자열로 class를 보관하기 때문에 유사배열 객체로 구성된 classList가 사용하기 더 편리하다. classList는 메서드도 제공한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!DOCTYPE html>
<html>
<head>
<style>
.red {
color: red;
}
.big {
font-size: 10em;
}
.small {
font-size: 1em;
}
</style>
</head>
<body>
<ul class="todos">
<li id="1">HTML</li>
<li id="2">CSS</li>
<li id="2">JS</li>
</ul>
<script>
document.getElementById("1").classList.add("red", "big"); // red big 적용
document.getElementById("1").classList.remove("red"); // big 적용
document.getElementById("1").classList.contains("big"); // ture (적용 여부)
document.getElementById("1").classList.replace("big", "small"); // small (교체)
document.getElementById("1").classList.toggle("red"); // small red (없으면 추가)
document.getElementById("1").classList.toggle("red"); // small (있으면 삭제)
</script>
</body>
</html>

요소에 적용되어 있는 CSS 스타일 참조

style 프로퍼티는 인라인 스타일만 반환한다. 따라서 클래스를 적용한 스타일이나 상속을 통해 암묵적으로 적용된 스타일은 style 프로퍼티로 참조할 수 없다. HTML 요소에 적용되어 있는 모든 CSS 스타일을 참조해야 할 경우 getComputedStyle 메서드를 사용한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<!DOCTYPE html>
<html>
<head>
<style>
body {
color: red;
}
.box {
width: 100px;
height: 50px;
background-color: cornsilk;
border: 1px solid black;
}
</style>
</head>
<body>
<div class="box">Box</div>
<script>
const $box = document.querySelector(".box");

// .box 요소에 적용된 모든 CSS 스타일을 담고 있는 CSSStyleDeclaration 객체를 취득
const computedStyle = window.getComputedStyle($box);
console.log(computedStyle); // CSSStyleDeclaration

// 임베딩 스타일
console.log(computedStyle.width); // 100px
console.log(computedStyle.height); // 50px
console.log(computedStyle.backgroundColor); // rgb(255, 248, 220)
console.log(computedStyle.border); // 1px solid rgb(0, 0, 0)

// 상속 스타일(body -> .box)
console.log(computedStyle.color); // rgb(255, 0, 0)

// 기본 스타일
console.log(computedStyle.display); // block
</script>
</body>
</html>

getComputedStyle 메서드의 두 번째 인수(pseudo)로 :after, :before와 같은 의사 요소 를 지정하는 문자열을 전달할 수 있다. 의사 요소가 아닌 일반 요소의 경우 두 번째 인수는 생략한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>
<html>
<head>
<style>
.box:before {
content: "Hello";
}
</style>
</head>
<body>
<div class="box">Box</div>
<script>
const $box = document.querySelector(".box");

// 의사 요소 :before의 스타일을 취득한다.
const computedStyle = window.getComputedStyle($box, ":before");
console.log(computedStyle.content); // "Hello"
</script>
</body>
</html>

이벤트

이벤트 드리븐 프로그래밍

이벤트가 발생했을 때 호출될 함수를 이벤트 핸들러(event handler)라 하고, 이벤트가 발생했을 때 브라우저에게 이벤트 핸들러의 호출을 위임하는 것을 이벤트 핸들러 등록이라 한다. 프로그램의 흐름을 이벤트 중심으로 제어하는 프로그래밍 방식을 **이벤트 드리븐 프로그래밍(event-driven programming)**이라 한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<button>Hello</button>
<script>
document.querySelector("button").onclick = () => {
console.log("Hello");
};
</script>
</body>
</html>

이벤트 핸들러 등록

이벤트 핸들러 어트리뷰트 방식

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html>
<body>
<button onclick="sayHi('Lee')">Click me!</button>
<!-- <button onclick="console.log(`Hi!`);">Click me!</button -->
<script>
function sayHi(name) {
console.log(`Hi! ${name}.`);
}
</script>
</body>
</html>
이벤트 핸들러 어트리뷰트 값으로 함수 참조가 아닌 인수 전달을 위힌 함수 호출문 등의 문을 할당한다. onclick 어트리뷰트 값은 onclick이란 함수 이름을 가진 함수 몸체 안에 들어오는 문들을 넣어주는 것과 마찬가지다.

이벤트 핸들러 프로퍼티 방식

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input id="username" type="text" placeholder="username">
<span class="display"></span>
<script>
const $username = document.getElementById('username');
const $display = document.querySelector('.display');

$username.oninput = () => {
$display.textContent = $username.value;
};
</script>
</body>
</html>

todoList 간단하게 만들어보기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>

<body>
<form>
<input class="input-todo" type="text" placeholder="enter todo!" />
<!-- 버튼 타입을 버튼으로 지정하지 않으면 submit이 기본값 -->
<button class="add">Add</button>
</form>

<ul class="todos"></ul>

<script>
const $form = document.querySelector("form");
const $inputTodo = document.querySelector(".input-todo");
// const $add = document.querySelector('.add'); // submit 버튼을 add로 대체
const $todos = document.querySelector(".todos");

const addTodo = () => {
const { value } = $inputTodo;
if (!value) return;

// $todos.innerHTML += `<li>${value}</li>`;
const $li = document.createElement("li");
const $checkbox = document.createElement("input");
const $span = document.createElement("span");
const $remove = document.createElement("button");

$checkbox.setAttribute("type", "checkbox");
$span.textContent = value;
$remove.classList.add("remove");
$remove.textContent = "X";

$li.appendChild($checkbox);
$li.appendChild($span);
$li.appendChild($remove);
$todos.appendChild($li);

$inputTodo.value = "";
$inputTodo.focus();
};

// $add.onclick = addTodo;

// $inputTodo.onkeyup = e => {
// if (e.key !== 'Enter') return;
// addTodo();
// };

$form.onsubmit = (e) => {
e.preventDefault();
addTodo();
};
</script>
</body>
</html>

Nyong’s GitHub