-1

I have been trying to use an attribute from an Object that I've used before and the second time I call it in another function it comes as undefined. I have checked with console.log its values and appears assigned. Does anyone knows whats I'm getting wrong ?

class Tab {
    thing: Thing;
    thingHistory: ThingHisotry;
    response: HttpResponse;
    request: HttpRequest;
    status: "sending" | "waiting";
    element: Element;

    constructor() {

        // Tab Element
        const tabElement = document.createElement('li');
        tabElement.classList.add('tagElement');

        // Tab Element Wrapper
        const tabElementWrapper = document.createElement('div');
        tabElementWrapper.classList.add('playNameDiv');
        tabElementWrapper.innerHTML = `
            <button>
                <span class="material-symbols-outlined">play_circle</span>
            </button>
            <p>${(this.thing) ? this.thing.name : 'Thing 1'}</p>
        `;

        // Tab Close Button
        const tabCloseBtn = document.createElement('button');
        tabCloseBtn.setAttribute('type', 'button');
        tabCloseBtn.classList.add('closeTagButton');
        tabCloseBtn.innerHTML = `<span class="material-symbols-outlined">close</span>`;
        tabCloseBtn.addEventListener('click', this.remove);

        tabElement.appendChild(tabElementWrapper);
        tabElement.appendChild(tabCloseBtn);

        this.element = tabElement;   -----> This atribute
        console.log(this.element) 
    }

    remove() {
        console.log(this.element);

        this.element.remove();   -------> Appears undefined the second time
    }

}

enter image description here

Aleix
  • 117
  • 1
  • 7

1 Answers1

1

You lost this reference

tabCloseBtn.addEventListener('click', this.remove.bind(this));
Konrad
  • 21,590
  • 4
  • 28
  • 64
  • that has resolved my problem but do you mind explaining the why it works or linking a page where I can read about it ? What it means that the reference it's "lost" ? – Aleix Sep 16 '22 at 11:37
  • 1
    https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback – Konrad Sep 16 '22 at 11:56