LoginSignup
2
0

More than 1 year has passed since last update.

JSPrimerのTodoアプリにて、個人的に謎な2点。

Posted at

確実に初心者な疑問なんだろうなと思う・・・・

※ 以下のソース部分は、JSPrimerさんより引用しています。
  https://jsprimer.net/use-case/todoapp/form-event/

<ul />が何故、<ul></ul>に変換されるの?

[A]部のconsole.logの結果が、<ul></ul>となる。
タブ関数element

element`<ul />`

の引数にテンプレートリテラルが存在しないので、stringsには<ul />がそのまま入っていて、reduceの内部は実行されていない。
それなのに何故、その結果のtodoListElement<ul></ul>に変換されいるのだろうか???

console.logって、なんか順番通り実行されない?

[B-1]、[B-2]、[B-3]の3か所で行っているconsole.log、この結果が全て

<ul>
  <li> (inputElement.valueの内容) </li>
</ul>

個人的にこの結果は、[B-3]直後のconsole.logだけで想定していたのですが・・
[C]を追加するとエラーCannot access 'todoItemElement'になるので、順番通り、意図したタイミングでconsole.logが実行されているのは間違いないと思うのです。全く分かりません。。

いずれにしても、その都度内容を確認したい場合はどう書いたらいいんだろう?

src/App.js
import { element, render } from "./view/html-util.js";

export class App {
    mount() {
        const formElement = document.querySelector("#js-form");
        const inputElement = document.querySelector("#js-form-input");
        const containerElement = document.querySelector("#js-todo-list");
        const todoItemCountElement = document.querySelector("#js-todo-count");

        const todoListElement = element`<ul />`;

        // [A]
        console.log(todoListElement);

        let todoItemCount = 0;
        formElement.addEventListener("submit", (event) => {

            event.preventDefault();

        // [B-1]
            console.log(todoListElement);
        // [C]
            console.log(todoItemElement);
            const todoItemElement = element`<li>${inputElement.value}</li>`;

        // [B-2]
            console.log(todoListElement);
            todoListElement.appendChild(todoItemElement);

        // [B-3]
            console.log(todoListElement);

            render(todoListElement, containerElement);

            todoItemCount += 1;
            todoItemCountElement.textContent = `Todoアイテム数: ${todoItemCount}`;

            inputElement.value = "";
        });
    }
}
src/view/html-util.js

...

export function htmlToElement(html) {
    const template = document.createElement("template");
    template.innerHTML = html;
    return template.content.firstElementChild;
}

export function element(strings, ...values) {
    const htmlString = strings.reduce((result, str, i) => {
        const value = values[i - 1];
        if (typeof value === "string") {
            return result + escapeSpecialChars(value) + str;
        } else {
            return result + String(value) + str;
        }
    });
    return htmlToElement(htmlString);
}

...

2
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0