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

179
Vistas
¿Cómo agregar eventlistener que no está dentro del componente?

Tengo un archivo js de componente web, es un componente de formulario de producto:

 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 } } } }

Tengo otro archivo js, es un eventlister para otro botón:

 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 } }

Soy un novato de javascript, si alguien puede ayudar, ¡se lo agradezco mucho!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

  1. Agregue un controlador para la llamada externa en su clase.
  2. Haga que su instancia de ProductForm sea accesible (expórtela).
  3. Llame a su nuevo método de clase en la instancia de su ProductForm.

Vea el ejemplo de código a continuación. Los ajustes pueden ser necesarios dependiendo de su implementación real.

 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 Denunciar
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