Steps for invoking a Polymer dialog within a JavaScript function

Dealing with Javascript scopes has always been a struggle for me.

My goal is to display a loading dialog while waiting for a JSON response, as shown below:

          toQueueRequest.onreadystatechange = function () {
          if (toQueueRequest.readyState === 4 && toQueueRequest.status === 200) {
              this.$.processingDialog.close();
              this.$.confirmDialog.open();
          } else if (toQueueRequest.readyState === 4){
            this.$.processingDialog.close();
            this.$.errorMsg="An error has occurred!"
            this.$.errorDialog.open();
          }
      };
      //var data = JSON.stringify({"RestoCode": window.location.pathname, "Fingerprint": this.finger});
      if (this.sector == "Any") {this.sector = null;};
      var data = JSON.stringify({"RestoCode": restoCode, "Fingerprint": finger, "PhoneNumber": this.cellno, "PersonalName": this.name, "QuantityPeople": this.pas, "SectorId": this.sector});
      toQueueRequest.send(data);

      this.$.reviewDialog.close();
      this.$.processingDialog.open();

However, when inside the onreadystatechange function, this.$.ProcessingDialog is not defined.

How can I access it from within?

Thank you very much!

Answer №1

This question isn't specifically about Polymer; it's actually a common issue with scoping. The problem arises when the `this` keyword inside your callback function doesn't refer to your component, but instead refers to the function itself. A common workaround for this issue has been to store a reference to the correct context in another variable. So, before your callback function, you would typically do something like

var that = this;

Then, within your function, you would use this new variable like so:

that.$.processingDialog.close();

Alternatively, if you are able to use ES6 features and depending on your build process or target browser support, you could utilize the arrow function syntax. This syntax does not create a new `this` context, so you could simply change:

toQueueRequest.onreadystatechange = function () {
  // ..
}

to

toQueueRequest.onreadystatechange = () => {
  // ..
}

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

Vue.js Applications tend to encounter Expected Errors originating from JavaScript

I've been diving into learning Vue.js using Visual Studio 2017. Currently, my goal is to create applications with multiple buttons that trigger the display of a message upon being clicked. However, when I attempt to run this code, I encounter the foll ...

The combination of Node.js and a Telegram bot

I am trying to utilize a telegram bot to access a specific route on a website. Within the website's routes.js file, I have: app.get('/api/getalert', getAlert); and var getAlert = function(req, res) { var id = req.query.id; ...

Guide on receiving application/csp-report as json in an express application utilizing bodyParser

I am currently working on creating a middleware that can receive CSP reports from browsers. Browsers send these reports with the Content-Type of application/csp-report, and the data is in JSON format. Right now, I'm using bodyParser.text to handle thi ...

Utilizing Facebook's UI share URL parameters within the Facebook app on mobile devices

Encountering an issue with the Fb ui share functionality on certain smartphones Here is the function: function shareFB(data){ FB.ui({ method: 'share', href: data, }, function(response){}); } Implemented as follows: $urlcod ...

Trouble fetching the concealed field data within the MVC framework

Upon executing the code provided below on an ASP.NET web form, I noticed that the value of the hidden field customerDeviceIdReferenceCode appears in the page source. <div id="customerDeviceIdReferenceCode" style="display:none;"> <inpu ...

Tips for effectively managing Angular JS dependencies and promoting modularity

As I embark on a new project from the ground up, my main focus is creating a responsive website optimized for mobile devices. In order to achieve this goal, I am seeking information about Angular: How does Angular manage its resources and dependencie ...

Troubleshooting issue with jquery.i18n.properties functionality

I am encountering an issue with implementing jQuery internationalization. I have included the files jquery.i18n.properties.js, jquery.i18n.properties-min.js, and jquery-min.js in my resources folder. In my jsp, I have added the following code: <script ...

Trouble expanding Bootstrap Dropdown menu on mobile devices

I am currently facing an issue with a Bootstrap navbar that includes a dropdown menu for selecting courses. On my desktop, everything works perfectly fine when I click on the courses tab. However, when I try to select a course on mobile, nothing happens. ...

Exploring the next() function in the Next JS API: A practical guide similar to Express JS

When creating an API in Next JS, I encountered an issue while passing three parameters to my API function (req, res, next). Take a look at the code snippet below: import catchAsyncErrors from "../../../middleware/catchAsyncErrors.js"; import conn ...

What is the procedure for including a js file in typescript?

I am trying to import a js file in typescript and access objects and functions within the file. I have added the js file in index.html, but it is not working as expected. I tried using "import '[js file path]'" but it did not work. import { Comp ...

Implementing a Class Addition Functionality Upon Button Click in AngularJS

I have a form that initially has disabled fields. Users can only view the information unless they click the edit button, which will enable the fields with a new style (such as a green border). I want to add a class to these fields that I can customize in m ...

Tips on running jQuery scripts when a div changes its display style from none to block?

Is there a way to trigger jQuery code when the style of a div transitions from `display: none;` to `display: block;`? I am working with tabs, which is why this div's style changes in this manner. The jQuery code should only be executed when this spec ...

Numerous intersecting lines on display within Google Maps

Currently, I am working on displaying multiple flight routes on Google Maps. I have implemented polylines with geodesic to achieve this functionality successfully. However, a challenge arises when more than two flights intersect the same route, causing o ...

Issue with the Ajax auto-complete feature in Internet Explorer

I am facing an issue with my "ajax suggestion list" getting hidden behind the "select menu" located right below the text box that triggers the ajax function. This problem only occurs in IE 6.0, while it works fine in other browsers. I have already disabled ...

When the anchor tag is clicked, I'm displaying the DIV for Customer Testimonials, however, the expansion of its height is not

One way to display customer testimonials is by using flexslider to create a horizontal scroll. The testimonials are hidden and only shown when the "view all testimonials" link is clicked, which can be seen in this JSFiddle example: Working : Demo JQuery ...

Enzyme's simulate() failing to produce expected results with onChange event

I am facing an issue with a component and its related tests: import React from 'react'; import PropTypes from 'prop-types'; function SubList (props) { var subways = ['', '1', '2', '3', & ...

Display JSON information in the present moment

I am looking to display only 2 results from a JSON file based on the current time. For example, at 11:00 am today, I want to show only the second and third items. JAVASCRIPT $(data.users).each(function() { var output = "<ul><li>" + this.first ...

Issue with MongoDB find() function not retrieving any results (Assignment)

I am currently working on an assignment that requires the use of noSQL databases. Although I understand most of the queries we have to perform in mongoDb, every query I execute seems to return a blank result. Initially, we are required to create a collect ...

Unable to send image file and string via XHR is causing issues

This task may seem straightforward, but I've been struggling with it for hours. My goal is to upload an image file along with stringified coordinates to crop the image on the server-side. Below is my client-side code: var formdata = new FormD ...

Using jQuery to dynamically retrieve a radio button

After struggling with this issue for quite some time, I have come to the realization that it's too complex for me to handle on my own. I could really use some assistance here. The problem at hand involves a page displaying various products, each of w ...