Writing a Vanilla JavaScript Class
Now let's write a class in a separate file. We will use some really useful proposals like the
nullish coalescing operator, string templates, private class properties or class getter and setter.
All these proposals will be transpiled into JavaScript that runs in mostly each relevant browser out
there:
src/amazing-button-vanilla.js
| export default class {
#maximumNumber = 9;
#button;
get maximumNumber() {
return this.#maximumNumber;
}
set maximumNumber(value) {
this.#maximumNumber = value;
this.#button.innerHTML = `Show number from 1 to ${this.#maximumNumber}`;
}
constructor(element) {
console.debug("Starting Vanilla Button");
element.style.border = "1px solid red";
element.style.textAlign = "center";
this.#button = document.createElement("button");
this.#button.innerHTML = `Show number from 1 to ${this.#maximumNumber}`;
this.#button.style.marginTop = "20px";
this.#button.addEventListener("click", () => {
resultDiv.innerHTML = Math.floor(Math.random() * this.#maximumNumber);
});
element.appendChild(this.#button);
let resultDiv = document.createElement("div");
resultDiv.style.border = "1px solid blue";
resultDiv.style.margin = "20px";
resultDiv.innerHTML = "No Result";
element.appendChild(resultDiv);
}
}
|
Next we will write a small helper function which creates some HTML code and inserts this into our
HTML body:
src/create-test-container.js
| export default function (caption, id) {
document.body.insertAdjacentHTML(
"afterbegin",
`
<div class="test-container">
<h4>${caption}</h4>
<hr />
<div id="${id}"></div>
</div>
`
);
}
|
Now let's remove our document.write("Hello World!");
from our index.js
and use our function to
create a new testing container and then load our class into this new container:
src/index.js
| import createTestContainer from "./create-test-container";
import { default as MyVanillaApp } from "./amazing-button-vanilla";
createTestContainer("Testing Vanilla JS", "test-container-vanilla");
let myVanillaInstance = new MyVanillaApp(
document.getElementById("test-container-vanilla")
);
|
With npm start
you should now see a page with a button. Pressing the Button will display a random
number from 0 to 9 in the box below.
Let's try our class setter and raise the maximum number to 99:
src/index.js
| import createTestContainer from "./create-test-container";
import { default as MyVanillaApp } from "./amazing-button-vanilla";
createTestContainer("Testing Vanilla JS", "test-container-vanilla");
let myVanillaInstance = new MyVanillaApp(
document.getElementById("test-container-vanilla")
);
myVanillaInstance.maximumNumber = 99;
|
Now the button generate numbers from 0 to 99.