Quiero agregar un observador de mutación en mi código y en este observador trato de llamar a otra función, pero dentro del observador de mutación "esto" parece no estar definido. También intenté usar bind en mi función onObserve (como this.onObserver.bind(this) ) pero eso tampoco parece funcionar.
Ah, y si es posible, no quiero usar algo como instance = this; porque si no recuerdo mal, esta no es la mejor práctica.
Aquí está mi código:
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); }