I have a Javascript class which each instance is attached to a DOM object. That class contains a method to hide the DOM object. For example
index.html
<div id="myDomObject">Content</div>
main.js
class MyClass {
constructor(element)
{
this.component = element;
}
hideElement()
{
this.component.classList.add('hidden');
}
}
let myDiv = new MyClass(document.getElementById("myDomObject");
I have a series of other classes which will also hide the same DOM object after something happens, such as the click of a button or result of an ajax request.
main2.js
class MySecondClass {
constructor(element)
{
this.component = element;
this.addClickEvent(some_button);
}
addClickEvent(element)
{
element.addEventListener('click', function()
{
document.getElementById("myDomObject").classList.add('hidden');
}
}
}
It doesn’t feel right to re-create the same method over and over again in each of my classes, just to replicate the method of the original class. That is not very DRY. What I would like to do is call the ‘hide’ method of this original class
I have tried this as below
class MySecondClass {
constructor(element)
{
this.component = element;
this.addClickEvent(some_button);
this.domObject = new MyClass(document.getElementById("myDomObject");
}
addClickEvent(element)
{
element.addEventListener('click', function()
{
this.domObject.hide();
}
}
}
This obviously instantiates multiple instances of the main class. If I have ten other classes, I will be calling those ten classes and then ten instances of the main class. Event listeners are added to the DOM object ten times etc.
How can I achieve this without overloading class instantiations?