Tips for preventing the occurrence of numerous instances of braintree.setup in Angular

I am encountering an issue with a Braintree payment form displayed in a modal window:

$scope.displayModalBraintree = function () {
    $scope.modal = 'modal_payment_form.html', $scope.$on('$includeContentLoaded', function () {
        braintree.setup('tokenStringFromServer', 'paypal', {
            container: 'paypal',
            locale: 'da_dk',
            onReady: function (integration) {
                console.log('ready', integration)
            }
        })
    })
})

When I click the button to trigger displayModalBraintree, everything works correctly the first time. However, if I click the button again, two Paypal buttons appear and the log shows "ready ready".

I have attempted to resolve this issue by using the teardown method as suggested at https://github.com/braintree/braintree-web/issues/29#issuecomment-137555915, but it has not resolved the problem.

Answer №1

Just to be transparent: I am employed at Braintree. If you need more assistance, feel free to reach out to our support team.

The issue arises from constantly adding a new listener for $includeContentLoaded each time $scope.displayModalBraintree is called without cleaning up the previous listeners. This leads to multiple calls of braintree.setup. For instance, if you run it a second time, braintree.setup gets executed twice. And with each subsequent invocation, the function runs multiple times.

An effective solution could involve defining the listener outside of $scope.displayModalBraintree as shown below:

var clientToken, braintreeVault;

$scope.$on('$includeContentLoaded', function () {
  braintree.setup(clientToken, 'paypal', {
    container: 'paypal',
    onReady: function (integration) {
        braintreeVault = integration;
    }
  })
});

$scope.displayModalBraintree = function () {
  $scope.getToken().then(function (token) {
    clientToken = token;
    $scope.modal = 'modal_payment_form?' + (new Date().getTime());
  })
};

Alternatively, you could consider destroying the listener after the modal loads, but moving it outside of $scope.displayModalBraintree seems like a more logical approach.

Answer №2

I am a part of the team at Braintree.

Our documentation on teardown has been recently updated since the comment on Github was made. To resolve any issues, you can try adding integration = null in your teardown function, as shown in this example code snippet. If that solution does not work, please share the code where teardown is called so we can assist you further.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporating an external TypeScript script into JavaScript

If I have a TypeScript file named test.ts containing the code below: private method(){ //some operations } How can I access the "method" function within a JavaScript file? ...

Error during the production build of Next.js Internationalized Routing: Prerendering page encountered an unexpected issue

The configuration in my next.config.js file looks like this: module.exports = withBundleAnalyzer({ i18n: { locales: ['en', 'es'], defaultLocale: 'en', localeDetection: false, }, ... }); This setup allows for ...

Is there a way to stop the page from scrolling once I reach the bottom of a specific div within it?

My webpage has multiple divs that share a similar structure: <div style="height:200px; overflow:auto;"> <div style="height:300px;"> <!--There is a lot of content here--> </div> </div> When the user hovers ove ...

Use Javascript's JQuery library to apply functionality to a newly inserted and cloned

I am facing an issue while trying to implement JQueryUI's DatePicker on a node. It works perfectly fine for all the existing nodes, but when I use the clone function to add new nodes, it doesn't seem to apply as expected. Here is the function th ...

Chosen Dropdown selection - Retrieve/Receive information

One of the challenges I'm facing involves a dropdown list on my web form that contains various dates. My main query is: How can I retrieve data for the selected date from a MySQL database and present it to the user? Additionally, if the chosen date do ...

How to create a transparent background on a canvas

Looking for help with analyzing my HTML, CSS, and JavaScript (THREE.js) code to achieve the desired output mentioned in the title. //**MY HTML CODE** <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8&qu ...

Improving Zen Coding to integrate with JavaScript files on Sublime Text2

Sublime Text2 is hands down my go-to editor, except for one minor hiccup - the Zen Coding plugin only works with CSS and HTML files. There are plenty of times where I'd love to use Zen Coding with JavaScript or other file types, like incorporating HTM ...

How do I set up a timing mechanism in a VSCode extension to automatically clear error messages after a specified duration?

I'm currently in the process of developing a VSCode extension, and ran into an issue where I need to display an error message if a certain condition is met. However, I want this error message to automatically disappear after a set amount of time (say, ...

Show the selected checkbox options upon clicking the submit button

Having trouble setting up a filter? I need to create a feature where checked values from checkboxes are displayed in a specific div after submitting. The display should include a 'Clear All' button and individual 'X' buttons to remove e ...

I provided Array.Filter with a function instead of a predicate, and surprisingly it gave back the entire array. How is that possible?

I encountered an unusual scenario where I passed a function instead of a predicate to Array.filter. This function modified individual student objects and the filter returned the whole array. This led me to question, why is this happening? According to co ...

What is the process for retrieving an excel file from the backend to the frontend?

I am currently facing an issue where I want to initiate a browser download of an excel file that is generated in my backend. However, I am struggling to figure out how to pass this type of response. app.get('/all', function (req, res) { db.q ...

Establishing the Backbone router configuration

Having trouble identifying the issue with my Backbone router. Is there an error within this code block? The index route is functioning correctly, but the classes route doesn't seem to be triggered (for example, when I try navigating to a URL like loca ...

Experiencing difficulties coding SVGs

Struggling with manipulating SVGs in JavaScript and looking to extend a line by clicking a button? Check out this code snippet I've included in the head tag: <script type="text/javascript"> x=135; y=135; var container = document.getElementById( ...

Is there a way to extract specific data from a JSON file and calculate the average in order to generate a line graph using JavaScript

I am working with data in json format and I want to create plots using plotly js. Specifically, I need to generate a plot showing different states by semester. To do this, I first need to filter the data for each state (for example, California), calculate ...

Ways to resolve the error "Expected an assignment or function call but found an expression with no-unused-expressions"

Issue : Error in ./src/components/main.js Line 7: No function call or assignment found, only an expression is present (no-unused-expressions) Search for the specific keywords to get more information on each error. import React from 'react'; ...

What could be the reason why both the add and remove functions are unable to work simultaneously within a JavaScript function?

Hi there! I recently started diving into JavaScript and encountered a little hiccup. I've been working on a dice game where images change randomly whenever a button is clicked. The images transition from one to another, but I wanted to add a rolling ...

Node js does not support iteration for DirectoryFiles

I am currently working on a program aimed at mapping all the json files within a specific directory. As I am new to JavaScript, this inquiry may not be ideal or obvious. Here is my code: const fs = require('fs'); const { glob } = require('gl ...

How to toggle a class using ng-click in AngularJS

Currently, I am working on a project using AngularJS for my website. One specific feature involves having a form that is initially hidden with "display:none" set deliberately. There's also a button labeled create. My goal is to have the form toggle b ...

Encountering an undefined response in API call using Fetch with Express Nuxt

I've hit a roadblock with a task involving Express, API, and Fetch. I'm utilizing Nuxt along with Shopify API endpoints to retrieve data such as orders. Below is my express API Endpoint which should return an array of objects (orders). const bod ...

personalizing material-ui component styles – set select component color to be pure white

I am looking to implement a dropdown menu using material-ui components (refer to https://material-ui.com/components/selects/). To do so, I have extracted the specific component from the example: Component return <div> <FormControl variant="outli ...