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

185
Visualizações
How to add eventlistener not within the component?

I have a web component js file, it is product form component:

if (!customElements.get('product-form')) {
 customElements.define('product-form', class ProductForm extends HTMLElement {
    constructor() {
      super();
      this.form.addEventListener('submit', this.onSubmitHandler.bind(this)); 
      this.cart = document.querySelector('cart-notification');
    }

    onSubmitHandler(evt) {
      evt.preventDefault();
      const config = fetchConfig('javascript');
      config.headers['X-Requested-With'] = 'XMLHttpRequest';
      delete config.headers['Content-Type'];
      const formData = new FormData(this.form);
      fetch(`${routes.cart_add_url}`, config)
        .then((response) => response.json())
        .then((response) => {
            this.cart.renderContents(response);     //when item add //to cart, the 
                                                      //renderContents() will be called to 
                                                       //show cart notification
        }

    }


 }
}

I have another js file, it is a eventlister for another button:

document.addEventListener('event-after-cart-added', function() {
  request.open('GET', '/cart.js', true);
  request.onload = function() {
  var data = JSON.parse(this.response); 
   
  //Then I need to call the function renderContents() of the above ProductForm 
  // component, I need to pass the data into renderContents to trigger the cart 
   //notification


  }     



}

I am a javascript newbie, if anybody can help, it is greatly appreciated!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

  1. Add handler for the external call in your class.
  2. Make your instance of ProductForm accessible (export it).
  3. Call your new class method on the instance of your ProductForm.

See code example below. Adjustments may be neccessary depending on your actual implementation.

  customElements.define(
    'product-form',
    class ProductForm extends HTMLElement {
      constructor() {
        super();
        this.form.addEventListener('submit', this.onSubmitHandler.bind(this));
        this.cart = document.querySelector('cart-notification');
      }
      onSubmitHandler(evt) {
        evt.preventDefault();
        const config = fetchConfig('javascript');
        config.headers['X-Requested-With'] = 'XMLHttpRequest';
        delete config.headers['Content-Type'];
        const formData = new FormData(this.form);
        fetch(`${routes.cart_add_url}`, config)
          .then((response) => response.json())
          .then((response) => {
            this.cart.renderContents(response);
          });
      }
      // add a handler for the external call for renderContents
      afterCartAddedHandler(data) {
        // your logic here
        this.card.renderContents(data);
      }
    }
  );
}

// somewhere in your code you should istanciate ProductForm:
export const form = new ProductForm();

// in your event listener:
// (if needed import "form" from the place of instanciation with "new ProductForm")

document.addEventListener('event-after-cart-added', function () {
  request.open('GET', '/cart.js', true);
  request.onload = function () {
    var data = JSON.parse(this.response);
    // add a call to your newly added handler in ProductForm class:
    form.afterCartAddedHandler(data);
  };
});
about 4 years ago · Juan Pablo Isaza Relatório
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