Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

105
Visualizações
Using this in MutationObserver

I want to add a mutation observer in my code and in this observer I try to call another function, but inside the mutation observer "this" seems to be undefined. I also tried using bind on my onObserve function (like this.onObserver.bind(this)) but that also doesn't seem to do the trick.

Oh and if possible I don't want to use something like instance = this; because if I recall correctly this isn't best practice.

Here's my code:

init() {
    // Define cart button variable
    this.cartButton = this.el.querySelector('.header-cart-btn');

    this.observeCartBadgeValue();
}

showOrHideCart(value) {
    if (value > 0) {
        this.el.style.display = 'block';
    } else {
        this.el.style.display = 'none';
    }
}

onObserve() {
    return new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            if (mutation.type === 'childList') {
                const cartBadge = this.cartButton.querySelector('.header-cart-badge');
                const cartBadgeValue = parseInt(cartBadge.textContent);

                console.log(cartBadge);
                console.log(this);

                this.showOrHideCart(cartBadgeValue);
            }
        });
    });
}

observeCartBadgeValue() {
    // Define target node of the observer and the configs
    const target = this.cartButton;
    const config = { attributes: true, childList: true, CharacterData: true };

    // Create an observer instance
    let observer = this.onObserve();

    // Paste in the target node and the configs
    observer.observe(target, config);
}
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda