如何从 javascript 函数内部调用 Polymer 对话框

How to call a Polymer dialog from inside a javascript function

我总是用 Javascript 瞄准镜战斗。

我正在尝试在等待 JSON 响应时显示加载对话框,如下所示:

          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="Ha ocurrido un error!"
            this.$.errorDialog.open();
          }
      };
      //var data = JSON.stringify({"RestoCode": window.location.pathname, "Fingerprint": this.finger});
      if (this.sector == "Cualquiera") {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();

但是,当在 onreadystatechange 函数内部时,this.$.ProcessingDialog 未定义。

如何从内部调用它?

非常感谢!

这与 Polymer 本身无关,这是一个关于范围界定的常见问题。这里真正的问题是在你的回调中 this 没有引用你的组件,但它是那个函数的引用。解决这个问题的最常见方法一直是在另一个变量中备份您的上下文。所以在你的回调之前你会做类似

的事情
var that = this;

并且在你的函数中你会使用另一个变量,所以

this.$.processingDialog.close();

变成

that.$.processingDialog.close();

或者,根据您的构建过程或您想要支持的浏览器,如果您可以使用 ES6,the arrow function 语法不会创建新的 this,因此您可以只更改

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

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