【问题标题】:Uncaught Type Error Opening Dialog未捕获的类型错误打开对话框
【发布时间】:2018-06-21 22:50:20
【问题描述】:

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

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

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

未捕获的类型错误:无法读取未定义的属性“对话框”

有什么想法吗? 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.$是未定义的
  • 它似乎在抱怨我在 $ 之后放了什么
  • 因为$ 没有在this 中定义.... console.log(this.$); // undefined 我猜this 不是你想的那样
  • this.$ 未定义。尝试找出如何调用$
  • 这就是我引用论文对话框的方式

标签: javascript polymer polymer-2.x


【解决方案1】:

您收到此错误是因为 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();
}

【讨论】:

  • 打印“Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, ...}”
  • 你能发布更多你的代码吗?确定问题的根本原因会很有帮助。
  • 我的监听器在这里被调用:connectedCallback() { super.connectedCallback(); window.addEventListener('_GEtesterror', this._boundListener); console.log("connectedCallback 运行"); }
  • 尝试在 connectedCallback 函数中添加带有 .bind 的 _boundListener 函数,如下所示:this._boundListener.bind(this)
  • 这已经奏效了。感谢您的帮助,希望能够转发!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-05
相关资源
最近更新 更多