• 카테고리

    질문 & 답변
  • 세부 분야

    프론트엔드

  • 해결 여부

    미해결

이벤트 객체에 관하여

20.12.10 22:11 작성 조회수 128

1

질문대상 강의 : 1-5강 Todo list 

질문 내용 :

강의 10분~11분 사이에 보면, 아래와 같은 코드가 있습니다.

<input bind:value={title} 

type="text"

on:keydown={

(e)=>{e.key==='Enter' && createTodo()

}

여기서 bold 표시한 부분이 이해되질 않습니다. if 문과 동일하게 동작한다는 점은 이해되지만,

a.key 부분의 이벤트 객체가 이해되지 않습니다.

 'abc.가나다' 라는 형식이 있을때, abc라는 객체의 속성 중 '가나다'라는 속성을 선택하는 형식인 것으로 알고 있습니다.

이벤트 객체라 할때, js에서 keydown 등과 같은 이벤트를 사용하려면 그 이벤트를 내포하고 있는 document 객체이거나 window객체인 것으로 알고 있는데

위에서 적힌 'e'라는 것은 임의의 인자입니다.

여기서 질문드리고 싶은점은,

1. 인자로 e를 받아오려면, 함수 내부에 변수가 지정되어있어야하는데 위 코드의 익명함수에서 변수는 무엇인지?

2. e를 인자로 받아와서 e가 객체가 되었다면 그것이 key라는 속성을 포함하고 있는 것인지? 

이상입니다. 감사합니다.

답변 4

·

답변을 작성해보세요.

3

질문하신 내용을 보니 hat sonn 님께서 오해하시거나 잘못 알고 계신 부분이 있는 듯해서 말씀드리니 혹시라도 오해 없으셨으면 좋겠습니다.

질문하신, 

"이벤트 객체라 할때, js에서 keydown 등과 같은 이벤트를 사용하려면 그 이벤트를 내포하고 있는 document 객체이거나 window객체인 것으로 알고 있는데"

에서 제가 질문을 이해한대로라면 이 내용을 잘못 알고 계신 듯합니다.

click, keydown 같은 많은 이벤트는 어떤 요소에서도 적용될 수 있습니다. 

여기서 keydown 이벤트라는 것은 키를 누른(Keydown) 상황에 대한 정보를 담고 있는 Event 객체이고, 

Document 객체 혹은 Window 객체는 관련이 없습니다.

다음 코드처럼 요소에 이벤트를 등록하고 이벤트 객체를 출력해 보세요.

다음 내용으로,

(e) => { e.key === 'Enter' && createTodo() }

"위에서 적힌 'e'라는 것은 임의의 인자입니다."

에서 '임의의 인자'라는 것은 혹시 '전역 변수'를 의미하시는 걸까요?

만약 그 의미가 아니더라도 뭔가 오해가 있지 않나 생각합니다.

위 '화살표 함수'는 다음과 같이 여러 방법으로 표현할 수 있습니다.

그럼 정리하신 질문으로 돌아와서,

"1. 인자로 e를 받아오려면, 함수 내부에 변수가 지정되어있어야 하는데 위 코드의 익명함수에서 변수는 무엇인지?"

e는 매개변수(Parameter)이고 이미 화살표 함수에 지정되어 있습니다.

(e) => { } 의 화살표 함수 문법에서 e가 매개변수 선언입니다.

"2. e를 인자로 받아와서 e가 객체가 되었다면 그것이 key라는 속성을 포함하고 있는 것인지?"

네! 포함하고 있습니다.

요소에 적용된 이벤트에 따라 MouseEvent, KeyboardEvent 같은 다른 이벤트 객체를 반환할 수 있고,

그에 맞는 key와 같은 속성이 포함되어 있습니다.

1

hat sonn님의 프로필

hat sonn

질문자

2020.12.12

아하... 자세한 답변 정말 감사드립니다.

사실 코딩도 이제 시작했고 js와 함께 스벨트를 배우는 중이라,,, js개념이 명확히 자리잡지 못한것 같습니다. 해당부분 복습 진행하고 있습니다. 감사합니다

한가지만 더 질문드리고 싶습니다.

라이프사이클 부분 강의를 수강하며 잘 듣고 있었는데, 오늘 다시 강의를 들으며 VScode를 통해 코딩을 실행하려고 하니,

스벨트의 시작부분에서 계속 오류가 뜹니다.

오류가 발생하는 지점은  npm run dev 지점입니다.

[ vs code 실행 - 새 터미널- cd로 desktop 접근 - npx degit sveltejs/template lifemodule - cd lifemodule - code . - (새 vs code 창이 열린 뒤) npm i - npm run dev - 아래와같은 오류 발생

오류의 화면은 아래와 같습니다. 

오류의 뜻이 뭔말인지도 모르겠고,,, vs code를 재설치해보고 수차례 시도해보고, 구글링을 해봐도 잘 나오지 않아 이렇게 질문드립니다.

감사합니다!

npm install의 터미널 결과와 npm run dev를 포함한  결과를 워드와 이미지 형식으로 아래에 남깁니다.

Windows PowerShell

Copyright (C) Microsoft Corporation. All rights reserved.

새로운 크로스 플랫폼 PowerShell 사용 https://aka.ms/pscore6

PS C:\Users\joj05\desktop\life-module> npm install

npm notice created a lockfile as package-lock.json. You should commit this file.

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@~2.1.2 (node_modules\rollup\node_modules\fsevents):

win","arch":"any"} (current: {"os":"win32","arch":"x64"})

npm WARN svelte-app@1.0.0 No repository field.

npm WARN svelte-app@1.0.0 No license field.

added 96 packages from 131 contributors and audited 97 packages in 4.434s

5 packages are looking for funding

  run `npm fund` for details

found 0 vulnerabilities

PS C:\Users\joj05\desktop\life-module> npm run dev

> svelte-app@1.0.0 dev C:\Users\joj05\desktop\life-module

> rollup -c -w

rollup v2.34.2

bundles src/main.js → public\build\bundle.js...

[!] Error: Identifier directly after number (Note that you need plugins to import files that are not JavaScript)

src\App.css (1:13)

1: main.svelte-1tky8bj{text-align:center;padding:1em;max-width:240px;margin:0 auto}h1.svelte-1tky8bj{color:#ff3e00;text-transform:uppercase;font-size:4em;font-weight:100}@media(min-width: 640px){main.svelte-1tky8bj{max-width:none}}

                ^

Error: Identifier directly after number (Note that you need plugins to import files that are not JavaScript)

    at error (C:\Users\joj05\Desktop\life-module\node_modules\rollup\dist\shared\rollup.js:5265:30)     

    at Module.error (C:\Users\joj05\Desktop\life-module\node_modules\rollup\dist\shared\rollup.js:9835:16)

    at tryParse (C:\Users\joj05\Desktop\life-module\node_modules\rollup\dist\shared\rollup.js:9716:23)  

    at Module.setSource (C:\Users\joj05\Desktop\life-module\node_modules\rollup\dist\shared\rollup.js:10142:19)

    at ModuleLoader.addModuleSource (C:\Users\joj05\Desktop\life-module\node_modules\rollup\dist\shared\rollup.js:18312:20)

    at ModuleLoader.fetchModule (C:\Users\joj05\Desktop\life-module\node_modules\rollup\dist\shared\rollup.js:18368:9)

    at async Promise.all (index 1)

    at ModuleLoader.fetchStaticDependencies (C:\Users\joj05\Desktop\life-module\node_modules\rollup\dist\shared\rollup.js:18393:34)

    at async Promise.all (index 0)

    at ModuleLoader.fetchModule (C:\Users\joj05\Desktop\life-module\node_modules\rollup\dist\shared\rollup.js:18370:9)

[이미지파일]

0

hat sonn님의 프로필

hat sonn

질문자

2020.12.12

빠른 답변 감사합니다!

아래에 말씀하신 3개 파일 내용을 복사해서 남깁니다.

감사합니다.

-App.svelte 파일

<script>
    export let name;
</script>

<main>
    <h1>Hello {name}!</h1>
    <p>Visit the <a href="https://svelte.dev/tutorial">Svelte tutorial</a> to learn how to build Svelte apps.</p>
</main>

<style>
    main {
        text-align: center;
        padding: 1em;
        max-width: 240px;
        margin: 0 auto;
    }

    h1 {
        color: #ff3e00;
        text-transform: uppercase;
        font-size: 4em;
        font-weight: 100;
    }

    @media (min-width: 640px) {
        main {
            max-width: none;
        }
    }
</style>

-rollup.config.js 파일

import svelte from 'rollup-plugin-svelte';
import commonjs from '@rollup/plugin-commonjs';
import resolve from '@rollup/plugin-node-resolve';
import livereload from 'rollup-plugin-livereload';
import { terser } from 'rollup-plugin-terser';
import css from 'rollup-plugin-css-only';

const production = !process.env.ROLLUP_WATCH;

function serve() {
    let server;

    function toExit() {
        if (serverserver.kill(0);
    }

    return {
        writeBundle() {
            if (serverreturn;
            server = require('child_process').spawn('npm', ['run', 'start', '--', '--dev'], {
                stdio: ['ignore', 'inherit', 'inherit'],
                shell: true
            });

            process.on('SIGTERM', toExit);
            process.on('exit', toExit);
        }
    };
}

export default {
    input: 'src/main.js',
    output: {
        sourcemap: true,
        format: 'iife',
        name: 'app',
        file: 'public/build/bundle.js'
    },
    plugins: [
        svelte({
            compilerOptions: {
                // enable run-time checks when not in production
                dev: !production
            }
        }),
        // we'll extract any component CSS out into
        // a separate file - better for performance
        css({ output: 'bundle.css' }),

        // If you have external dependencies installed from
        // npm, you'll most likely need these plugins. In
        // some cases you'll need additional configuration -
        // consult the documentation for details:
        // https://github.com/rollup/plugins/tree/master/packages/commonjs
        resolve({
            browser: true,
            dedupe: ['svelte']
        }),
        commonjs(),

        // In dev mode, call `npm run start` once
        // the bundle has been generated
        !production && serve(),

        // Watch the `public` directory and refresh the
        // browser on changes when not in production
        !production && livereload('public'),

        // If we're building for production (npm run build
        // instead of npm run dev), minify
        production && terser()
    ],
    watch: {
        clearScreen: false
    }
};

-package.json 파일

{
  "name": "svelte-app",
  "version": "1.0.0",
  "scripts": {
    "build": "rollup -c",
    "dev": "rollup -c -w",
    "start": "sirv public"
  },
  "devDependencies": {
    "@rollup/plugin-commonjs": "^16.0.0",
    "@rollup/plugin-node-resolve": "^10.0.0",
    "rollup": "^2.3.4",
    "rollup-plugin-css-only": "^3.0.0",
    "rollup-plugin-livereload": "^2.0.0",
    "rollup-plugin-svelte": "^7.0.0",
    "rollup-plugin-terser": "^7.0.0",
    "svelte": "^3.0.0"
  },
  "dependencies": {
    "sirv-cli": "^1.0.0"
  }
}

0

작성하신 내용을 바탕으로 현재 의심되는 문제는,

- App.svelte 파일 오타
- 개발 서버 구동에 필요한 모듈 미설치
- 잘못된 Rollup 구성 

정도이고요,

일단 확인하면 도움이 될 수 있는 부분은,

- App.svelte
- package.json
- rollup.config.js

이렇게 3개 파일이고 각 파일 내용을 복사해서 답변에 남겨주시면 감사합니다.

만약 해당 파일 내용에서 문제를 발견하지 못하면 VS Code까지 재설치 하셨다고 하니,

원격 제어로도 도움을 드릴 수 있습니다.

그럼 답변 남겨주시면 바로 확인해 보겠습니다! 💻