beginner web dev here. I created a custom list component (with edit feature) in plain JS/HTML.
I have few questions on which I would like to get an answer (besides the normal feedback that you folks do here on the site):
is this a standard/right way to create and use components when using plain JS?
if I can create and use objects like this, what is the benefit of creating such component using say react.js?
ListComponent.js
///////
//
// ListComponent is a class which lets you create a list component
// dynamically using JS and DOM. The list component also has some features
// out of the box - e.g. editing items when clicked.
//
function ListComponent(type) {
// Model data of the list.
this.data = [{ name: "mona", id: 0 }, { name: "dona", id: 1 }, { name: "jona", id: 2 }],
// Create a list component.
this.create = function () {
let list = document.createElement(!type ? "ul" : type);
list.id = "customList";
document.body.appendChild(list);
this.draw();
},
this.remove = function () {
// Remove our list component from DOM
var elem = document.getElementById("customList");
return elem.parentNode.removeChild(elem);
}
///
// draw
// Appends items to the list component.
// Deletes any child items first if there are any.
//
this.draw = function () {
let that = this;
// First delete all items of the list.
let list = document.getElementById("customList");
while (list.firstChild) {
list.removeChild(list.firstChild);
}
// Now, append new items.
that.data.forEach(function (item) {
let listItem = document.createElement("li");
// Listen to click event on this list item.
listItem.addEventListener("click", function () {
let newName = prompt("Enter item name", item.name);
if (newName == null || newName.length == 0)
return;
// Make change in the list model data.
for (let i = 0; i < that.data.length; i++) {
if (that.data[i].id == item.id) {
that.data[i].name = newName;
break;
}
}
// Redraw the list.
that.draw();
}, false);
listItem.innerHTML = item.name;
listItem.id = item.id;
list.appendChild(listItem);
});
}
}
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Demo site</title>
<!-- Import our list component -->
<script src="ListComponent.js"></script>
</head>
<script>
document.addEventListener("DOMContentLoaded", function (event) {
// Run this code when DOM is loaded.
let list = new ListComponent("ol");
list.create();
});
</script>
</body>
</html>