Instead of selecting the controller, send an event handled by stripe-cards

Using a query selector to find controller in order to call method could be dangerous as the DOM can change. Using an event should be more robust.
This commit is contained in:
Jean-Baptiste Bellet
2023-01-18 11:40:28 +01:00
parent d2e6b7d164
commit 7320a1714c
3 changed files with 12 additions and 12 deletions

View File

@@ -12,17 +12,12 @@ export default class extends Controller {
selectPaymentMethod(event) {
this.setPaymentMethod(event.target.dataset.paymentmethodId);
const stripeCardSelector =
this.application.getControllerForElementAndIdentifier(
document
.querySelector(
`[data-paymentmethod-id="${event.target.dataset.paymentmethodId}"]`
)
.querySelector('[data-controller="stripe-cards"]'),
"stripe-cards"
);
stripeCardSelector?.initSelectedCard();
// Send an event to the right (ie. the one with the same paymentmethodId)
// StripeCardsController to initialize the form elements with the selected card
const customEvent = new CustomEvent("stripecards:initSelectedCard", {
detail: event.target.dataset.paymentmethodId,
});
document.dispatchEvent(customEvent);
}
setPaymentMethod(paymentMethodContainerId) {