首页 > 解决方案 > 触发全球事件 Polymer 2

问题描述

我正在尝试为我的界面创建一个错误处理对话框。该对话框将仅显示来自 Iron ajax 的错误消息。我能够访问此消息并希望在 ajax 返回错误时触发一个事件。这是触发事件的代码:

  testError(e) {
    const err = e.detail.request.xhr.response.message;
    this.dispatchEvent(new Event('error'));
  }

这是添加事件监听器的代码:

  class ErrorHandling extends Polymer.Element {
    static get is() { return 'error-handling'; }
    static get properties() {
      return {
      }
    }
    constructor() {
      super();
      this._boundListener = this.error.bind(this);
    }
    connectedCallback() {
      super.connectedCallback();
      window.addEventListener('error', this._boundListener);
      console.log("connectedCallback ran");
    }
    disconnectedCallback() {
      super.disconnectedCallback();
      window.removeEventListener('error', this._boundListener);
      console.log("disconnectedCallback ran");
    }
    _boundListener(e) {
      console.log("boundlistener ran");
    }

我已通读文档以尝试找出为什么这不起作用但没有成功。为什么这不起作用?

标签: javascriptpolymerpolymer-2.x

解决方案


您需要使用自定义事件。有了这个,你可以添加选项 bubbles: true 这将使事件冒泡直到它到达窗口。

this.dispatchEvent(new CustomEvent('error', {bubbles: true}));

要接收此事件,您必须注册一个事件侦听器:

window.addEventListener('error', this.myEventListener)

推荐阅读