未捕获的类型错误打开对话框

Uncaught Type Error Opening Dialog

我在 Polymer 2 中编码,并试图在函数运行时打开纸质对话框组件:

_boundListener(e) {
  this.error = e.detail;
  console.log(this.error);
  this.$.dialog.open();
}

我已经验证 this.error 是 运行 并且包含正确的数据。我的模板中有一个 id 为 dialog 的纸质对话框,但是当此函数运行时,我收到以下消息:

未捕获的类型错误:无法读取未定义的 属性 'dialog'

有什么想法吗? TIA

此函数在事件侦听器被触发时运行。该侦听器从此函数触发:

  testError(e) {
    const err = e.detail.request.xhr.response.message;
    window.dispatchEvent(new CustomEvent('_GEtesterror', {bubbles: true, detail: err}));
  }

我不得不使用 window.dispatchEvent 触发此事件,因为它没有冒泡到对话框所在的 html。这可能就是找不到 this.$.dialog?

的原因

这是监听器函数的样子:

connectedCallback() {
  super.connectedCallback();
  window.addEventListener('_GEtesterror', this._boundListener);
  this._boundListener.bind(this);
}
disconnectedCallback() {
  super.disconnectedCallback();
  window.removeEventListener('error', this._boundListener);
}
_boundListener(e) {
  this.error = e.detail;
  console.log(this, this.$);
  this.$.dialog.open();
}

您收到此错误是因为 this.$ 未定义。

使用console.log(this, this.$) 确定调用函数的范围。您的侦听器调用范围错误。

此外,将您的 _boundListener 绑定 到正确的范围:

connectedCallback() {
  super.connectedCallback();
  window.addEventListener('_GEtesterror', this._boundListener.bind(this));
}
disconnectedCallback() {
  super.disconnectedCallback();
  window.removeEventListener('error', this._boundListener.bind(this));
}
_boundListener(e) {
  this.error = e.detail;
  console.log(this, this.$);
  this.$.dialog.open();
}