Home>

There was an opportunity to touch javascript in class, so I'm trying to create a web service using only javascript.
Naturally, since it is only javascript, I am touching it with the feeling of what can be done rather than operation.
In this creation, a task management site is created and the flow is as follows.

  1. Click the plus button
  2. Task group div, first task and add task button
  3. Click the add task button to add a task
It is a simple flow like

.
How to write the code and error.

<! DOCTYPE html>
<html lang = "en">
<head>
    <meta charset = "UTF-8">
    <meta name = "viewport" content = "width = device-width, initial-scale = 1.0">
    <meta http-equiv = "X-UA-Compatible" content = "ie = edge">
    <link rel = "stylesheet" href = "../ css/style.css">
    <title>Document</title>
    <link rel = "stylesheet" href = "../ css/style.css">
    <script src = "../ javascript/taskbox.js"></script>
    <script src = "../ javascript/main.js"></script>
</head>
<body>
    You can add a task group by pressing the<p>+ button.</p>
    <svg xmlns = "http://www.w3.org/2000/svg" xmlns: xlink = "http://www.w3.org/1999/xlink" version = "1.1" preserveAspectRatio = "xMidYMid meet" viewBox = "0 0 640 640"><defs><path d = "M250 0L380 0L380 640L250 640L250 0Z" /><path d = "M0 250L640 250L640 350L0 350L0 250Z" /></defs><g><g><use xlink: href = "# ai3n3xJWd" opacity = "1" fill = "# 000000" fill-opacity = "1" />
    <g><use xlink: href = "# ai3n3xJWd" opacity = "1" fill-opacity = "0" stroke = "# ef1581" stroke-width = "0" stroke-opacity = "1" /></g ></g><g><use xlink: href = "# ceUN5fTae" opacity = "1" fill = "# 000000" fill-opacity = "1" /></g></g></svg>
     
</body>
</html>
// main.js
var task_box_group;
var task_boxCount = 0;
var taskGroup = [];
window.onload = function () {
    task_box_group = document.getElementById ("task_box_group");document.getElementById ("add_button"). addEventListener ("click", function () {
        taskGroup.push (new taskbox (task_box_group, String (task_boxCount)));
        task_boxCount ++;
    });
}
// taskbox.js
class taskbox {
    task_box = this.createTag ("div", {},

{'margin': '10px', 'float': 'left', 'width': '200px', 'height': '300px', 'background-color': 'rgba (255, 255, 255, 0.589) '});
    task = this.createTag ("input", {'type': 'text', 'placeholder': 'Please enter a task'},

('border-style': 'none', 'margin': '3px', 'border-radius': '3px', 'width': '180px'});
    button_task_add = this.createTag ("button", {},

{});
    taskCount = 0;
    parent;
    add_task_id;
    / **
     *
     * @param {HTMLElement} parent this contained html parent
     * @param {string} id this id
     * /
    constructor (parent, id) {
        this.task_box.id = id;
        this.parent = parent;
        this.task.id = this.task_box.id + this.taskCount;
        this.taskCount ++;
        this.button_task_add.innerText = "Add";
        this.button_task_add.id = this.task_box.id + "add";
        this.add_task_id = this.button_task_add.id;
        this.parent.appendChild (this.task_box);
        this.task_box.appendChild (this.task);
        this.task_box.appendChild (this.button_task_add);this.button_task_add.addEventListener ("click", this.task_add);
    }
    / **
     * @param element html tag name: string
     * @param attrs atatch atribute: Dictionary<string, string>{attrName: attrValue}
     * @param styles atatch style: Dictionary<string, string>{property: value}
     * @return HTMLElement
     * /
    createTag (element = "a", attrs, styles) {
        var tag = document.createElement (element);
        for (var attr in attrs) {
            tag.setAttribute (attr, attrs [attr]);
        }
        for (var style in styles) {
            tag.style.setProperty (style, styles [style]);
        }
        return tag;
    }
    task_add () {
        this.button_task_add.remove ();
        this.task.id = task_box.id + this.taskCount;
        this.task_box.appendChild (this.task)
        this.task_box.appendChild (this.button_task_add);
        this.taskCount ++;
    }
}
taskbox.js: 43 Uncaught TypeError: Cannot read property 'remove' of undefined
    at HTMLButtonElement.task_add (taskbox.js: 43)
task_add @ taskbox.js: 43


Click task add button and task_add will be executed
Whenever I try to use a class in JavaScript, I get this error.
I can't read it though I should have it, or even if I display this.task_box in console.log, I'm not sure if it is undefined.

Thanks for your response.

  • Answer # 1

    What should be initialized in the constructor instead of calling it with this. in the field declaration part?

    [Class # Field Declaration-JavaScript | MDN]
    https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes#Field_declarations

  • Answer # 2

    in the constructor,

    this.button_task_add.addEventListener ("click", this.task_add);


    About task_add

    task_add () {
      ...
    }


    Since this is written in this form, this is not lexical like the arrow function, but is bound dynamically.
    And addEventListener binds the DOM element where the event occurred to this of the function received as a callback.
    Reference: The value of this within the handler
    If you log like this ...

    task_add () {
      console.log (this);
      ...
    }


    In the chrome console, you can see thatis displayed.
    Since this is not a taskbox instance but a DOM element,this.button_task_add.remove ();returns undefined without the button_task_add property, and the errorCannot read property 'remove' of undefined at HTMLButtonElement.task_add

    The solution is
    Use bind () during addEventListener to fix to this in the current context

    this.button_task_add.addEventListener ("click", this.task_add.bind (this));


    Or
    Use an arrow function (with class field) to define task_add

    // task_add () {
    //…
    //}
    task_add = () =>{
      ...
    };


    I think that there is such a thing

Related articles