Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

103
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda