How to make event listener pull data from another div?

Viewed 105

I need to change the event listening to a class within the product div, but I want the function to still pull the data within the product div.. at the moment it has 'this.open();' so it's trying to find the data within the .available div (as far as I understand...), but it can't obviously. So I need the event listener to happen on click of .available but then search this.DOM.product.

Any idea how I can fix this? I'm not too familiar with DOM

  class Item {
      constructor(el) {
        this.DOM = {};
        this.DOM.el = el;
        this.DOM.product = this.DOM.el.querySelector('.product');
        this.DOM.productBg = this.DOM.product.querySelector('.product__bg');
        this.DOM.available = this.DOM.product.querySelector('.available');
        this.DOM.productImg = this.DOM.product.querySelector('.product__img');

        this.info = {
          img: this.DOM.productImg.src,
          title: this.DOM.product.querySelector('.product__title').innerHTML,
          subtitle: this.DOM.product.querySelector('.product__subtitle').innerHTML,
          description: this.DOM.product.querySelector('.product__description').innerHTML,
          price: this.DOM.product.querySelector('.product__price').innerHTML
        };

        this.initEvents();
      }
      open() {
        DOM.details.fill(this.info);
        DOM.details.open({
          productBg: this.DOM.productBg,
          productImg: this.DOM.productImg
        });
      }
      initEvents() {
        this.DOM.available.addEventListener('click', () => this.open());
      }

    };
1 Answers

I suspect that your problem is that this doesn't resolve to the Item instance within the event handler. That's because event handlers are not automatically bound to anything.

If that's the problem, you can fix it easily by explicitly providing a this value when you bind the event handler:

this.DOM.available.addEventListener('click', this.open, this);

I added a third argument to addEventListener; the argument is optional, and controls the value of this within the handler function.

Note: I also changed your handler from () => this.open() to just this.open. The reason is that you can't unbind an anonymous event handler, which means your current impl makes teardown impossible.

Related