Skip to content

Commit

Permalink
Avoid re-mounting elements if already in DOM (#151)
Browse files Browse the repository at this point in the history
* Avoid re-mounting elements if already in DOM

When checkout is updated, check if the elements are still mounted in the DOM before proceeding to re-mount.

* WP coding standards: use $ instead of jQuery

* WP coding standards: comma ending multiline object or array member
  • Loading branch information
dechov committed Jul 27, 2019
1 parent 71f177f commit d21233b
Showing 1 changed file with 9 additions and 4 deletions.
13 changes: 9 additions & 4 deletions assets/js/wc-payment-checkout.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* global jQuery, Stripe, wc_payment_config */
jQuery( function() {
jQuery( function( $ ) {
'use strict';

var stripe = new Stripe( wc_payment_config.publishableKey, {
Expand All @@ -16,7 +16,12 @@ jQuery( function() {
// Only attempt to mount the card element once that section of the page has loaded. We can use the updated_checkout
// event for this. This part of the page can also reload based on changes to checkout details, so we call unmount
// first to ensure the card element is re-mounted correctly.
jQuery( document.body ).on( 'updated_checkout', function() {
$( document.body ).on( 'updated_checkout', function() {
// Don't re-mount if already mounted in DOM.
if ( $( '#wc-payment-card-element' ).children().length ) {
return;
}

cardElement.unmount();
cardElement.mount( '#wc-payment-card-element' );
} );
Expand All @@ -34,7 +39,7 @@ jQuery( function() {

// Create payment method on submission.
var paymentMethodGenerated;
jQuery( 'form.checkout' ).on( 'checkout_place_order_woocommerce_payments', function() {
$( 'form.checkout' ).on( 'checkout_place_order_woocommerce_payments', function() {
// We'll resubmit the form after populating our payment method, so if this is the second time this event
// is firing we should let the form submission happen.
if ( paymentMethodGenerated ) {
Expand Down Expand Up @@ -64,7 +69,7 @@ jQuery( function() {
paymentMethodInput.value = id;

// Re-submit the form.
jQuery( '.woocommerce-checkout' ).submit();
$( '.woocommerce-checkout' ).submit();
} );

// Prevent form submission so that we can fire it once a payment method has been generated.
Expand Down

0 comments on commit d21233b

Please sign in to comment.