Today I Learned #4

loopbacksealยท2020๋…„ 12์›” 31์ผ
0

Javascript

๋ชฉ๋ก ๋ณด๊ธฐ
4/16
post-thumbnail

local storage

์–ด์ œ ์ž‘์„ฑํ–ˆ๋˜ clock.js๋ฅผ ๋‹ซ๊ณ , greeting.js๋ฅผ ์ƒˆ๋กœ ์ƒ์„ฑํ•˜์—ฌ index.html์— ์ถ”๊ฐ€ํ•ด ์ฃผ์—ˆ๋‹ค. ๋Š˜ ๊ทธ๋ ‡๋“ฏ ์‹œ์ž‘์€ divide๋ถ€ํ„ฐ

<script src="clock.js"></script>
<script src="greeting.js"></script>

usage

ํฌ๋กฌ์—์„œ ๊ฐœ๋ฐœ์ž ๋„๊ตฌ๋ฅผ ์‚ฌ์šฉํ• ๋•Œ, Elements, Console๊ณผ ๊ฐ™์€ ๋ฉ”๋‰ด์—์„œ Application์„ ํƒญํ•ด๋ณด๋ฉด, Storage ํ•ญ๋ชฉ ์ค‘ Local Storage๊ฐ€ ์žˆ๋Š” ๊ฒƒ์„ ํ™•์ธ ํ•  ์ˆ˜ ์žˆ๋‹ค.

Local Storage๋Š” ์ž‘์€ Javascript ์ •๋ณด๋“ค์„ ๊ฐ URLs ๋ณ„๋กœ ์‚ฌ์šฉ์ž์—๊ฒŒ ์ €์žฅํ•ด ๋‘๋Š” ๊ฒƒ์„ ๋งํ•˜๊ณ  (์ฆ‰, velog์˜ local storage์— ์ €์žฅ๋œ ๊ฐ’์„ naver์—์„œ ๋ถˆ๋Ÿฌ์˜ค๋Š” ๊ฒƒ์€ ๋ถˆ๊ฐ€๋Šฅ ํ•˜๋‹ค๋Š” ์˜๋ฏธ์ด๋‹ค), ์ƒˆ๋กœ๊ณ ์นจ์„ ํ•ด๋„ ๋ณ€ํ•˜์ง€ ์•Š๋Š”๋‹ค.
momentum์—์„œ ์‚ฌ์šฉ์ž์˜ ์ด๋ฆ„์„ ์ž…๋ ฅ๋ฐ›์•„, ์ƒˆ๋กœ๊ณ ์นจ ํ• ๋•Œ๋งˆ๋‹ค ๋ฌผ์–ด๋ณด๋Š” ์ผ์ด ๋ฐœ์ƒํ•˜์ง€ ์•Š๋„๋ก, form๊ณผ input์„ ํ†ตํ•ด ์ž…๋ ฅ๋ฐ›์•„ local storage์— ์ €์žฅํ•ด ๋ณผ ํ…๋ฐ, ๊ทธ ์ „์— Local Storage๊ฐ€ ์ž‘๋™ํ•˜๋„๋ก ํ•˜๋Š” ๋งค์ปค๋‹ˆ์ฆ˜์„ ์‚ฌ์šฉํ•ด๋ณด์ž.

        <form class="js-form form">
            <input type="text" placeholder="What is your name?"/>
        </form>
        <h4 class="js-greetings greetings"></h4>

์ด๋Ÿฌํ•œ ํ˜•ํƒœ๋กœ ์‚ฌ์šฉ์ž์˜ ์ž…๋ ฅ์„ ๋ฐ›๊ณ ์ž ํ•œ๋‹ค. class์ค‘ js-๊ฐ€ ๋ถ™์€ class๋Š” .js์˜ ๋‚ด๋ถ€์—์„œ ํ•ด๋‹น ํด๋ž˜์Šค๋ฅผ ์ง€์ •ํ•˜๊ธฐ ์œ„ํ•ด์„œ, ๋ถ™์ง€ ์•Š์€ class๋Š” css๋ฅผ ํ†ตํ•ด์„œ ๋ณ€๊ฒฝ์‹œํ‚ค๊ธฐ ์œ„ํ•ด ๋‘ class๋ฅผ ์ง€์ •ํ•ด์ฃผ์—ˆ๋‹ค.

.greetings {
  display: none;
}

.showing {
  display: block;
}

css์—์„œ๋Š” ์‚ฌ์šฉ์ž์˜ ์ด๋ฆ„์„ ๋ณด์ด๊ฒŒ ํ•˜๋Š” showing์ด๋ผ๋Š” class๋ฅผ ๋ฏธ๋ฆฌ ์ƒ์„ฑํ•ด์ฃผ๊ณ , ๊ธฐ์กด์˜ greetings๋Š” ๋ณด์ด์ง€ ์•Š๋„๋ก ํ•ด์ฃผ์—ˆ๋‹ค.

const USER_LS = "currentUser",
SHOWING_CN = "showing";

function paintGreeting(text) {
    greeting.classList.add(SHOWING_CN);
    greeting.innerText = `Hello ${text}!`;
}

function loadName() {
    const currentUser = localStorage.getItem(USER_LS)
    if(currentUser === null){

    } else {
        paintGreeting(currentUser);
    }
}

ํ›„์— greetings.js์—์„œ loadName()์„ ํ†ตํ•ด localStorage์˜ currentUser๋ผ๋Š” key์— ๋Œ€ํ•œ value๋ฅผ ์ €์žฅํ•˜๊ณ , ๋งŒ์•ฝ ๊ฐ’์ด ์กด์žฌํ•œ๋‹ค๋ฉด, paintGreeting์„ currentUser๊ฐ€ ์ธ์ž๋กœ ๊ฐ–๋„๋ก ํ•˜์—ฌ ์‹คํ–‰, greeting์˜ classList์— showing์„ ์ถ”๊ฐ€ํ•˜์—ฌ display: none; ์„ display: block;์ด ๋˜๋„๋ก ํ•˜์˜€๋‹ค.

๊ฐœ๋ฐœ์ž ๋„๊ตฌ๋ฅผ ์ด์šฉํ•˜์—ฌ currentUser์˜ ๊ฐ’์„ ์„ค์ •ํ•ด์ค€ ํ›„

์ƒˆ๋กœ๊ณ ์นจ์„ ํ•˜๋ฉด,,

์ •์ƒ์ ์œผ๋กœ ํ•จ์ˆ˜๊ฐ€ ์ž‘๋™ํ•จ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค!

profile
CAU Business Administration

0๊ฐœ์˜ ๋Œ“๊ธ€