DEV Community

artydev
artydev

Posted on

TodoList as CustomElement

Cherry on cake, we can create a customElement from our TodoApp in few lines :

import Todo from './todoapp.js';

class TodoList extends HTMLElement {
  constructor() {
    super();
    const todoapp = Todo(this).init(["first todo"]);
    this.appendChild(todoapp);
  }
}

window.customElements.define("todo-list", TodoList);
Enter fullscreen mode Exit fullscreen mode
<pre style="font-size:1.2rem">
  TodoList as Custom Element
</pre>

<todo-list></todo-list>
<hr />
<todo-list></todo-list>

Enter fullscreen mode Exit fullscreen mode

You can see it in action : TodoListCE

Top comments (2)

Collapse
 
efpage profile image
Eckehard

As far as I see, this is an implementation using a procedural approach, which is pretty ok. There is an example on the DML-homepage featuring a class based approach. Finally we see, there is not a big difference and a nice example to see the differences.

For me, it is more a tendency to build logical units following the functional structure. As there are multiple toDo´s with their individual state, each toDo is represented by an object of the class toDoObj. This object maintains all the functions of a todo element, the object is deleted when the toDo-Element is deleted. So it act´s as a digital twin.

The example features also some functions for persistence (saveData, readData), which are simple external functions that access data from the toDo-objects. With a more complex toDo-Element maybe the persistence functions should become part of the toDo class. But as we see, this is one of the decisions we have to make, and there are two valid answers.

So, we see that there is a pretty natural evolution from a procedural approach to a class based approach. Thank you for your example.

Collapse
 
artydev profile image
artydev

Thank's for taking time to comment Eckehard.
What I like about DML, it is that it does not force you to choose a particular paradigm.
It lends you quietly code as you like and enhance when you need.
Regards