0

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);
}
strayed soul
  • 67
  • 1
  • 7

0 Answers0