如何从Web组件Mixin中删除事件侦听器 - >属性“脱节”在类型的“ htmlelement”上不存在



我正在为Web组件构建一个打字稿Mixin,以添加阻力Behvior。到目前为止,一切都很好。但是,在断开可拖动的Web组件之后尝试删除事件侦听器时,我有一个困难的问题。

drag.ts - 将阻力行为添加到htmlelements

type Constructor = new (...args: any[]) => HTMLElement
export function Drag<BC extends Constructor>(BaseClass: BC) {
    return class Drag extends BaseClass {
        constructor(...args: any[]) {
            super(...args)
            // Somehow I need to remove this listener when the component is disconnected
            document.addEventListener(UPDATE_ACTIVE_DRAG_SET, this.handleToggleDrag)
        }
        disconnectedCallback() {
            // This mehods must be implemented by a web component
            // Not all web components that will receive the drag behavior 
            // will ahve a disconnectedCallback defined
            // So typescript must be right when it gives an error
            super.disconnectedCallback()
            // These work just fine (HTMLElement implements them)
            super.innerHTML
            super.querySelector('div')
        }
        // ...more stuff here
    }
}

main-menu.ts - 拖动行为的可能候选者

export class MainMenu extends HTMLElement{
    // ... implementation of the web component
    // <!> It is very likely that not all components will implement this
    disconnectedCallback() {} 
}
window.customElements.define('main-menu', DragAndDropLayout(MainMenu))

到目前为止,我唯一的想法是猴子修补htmlelement以包含一个虚拟disconnectedCallback,以便super.disconnectedCallback不会对此错误抱怨:Property 'disconnectedCallback' does not exist on type 'HTMLElement'。我还没有尝试过。是否有更好的解决方法?

您的混音可以测试超类中的方法:

disconnectedCallback() {
  if (super.disconnectedCallback) {
    super.disconnectedCallback();
  }
  // Do mixin work here.
}

大量使用Mixins的Elix项目在其Mixin方法和属性的组成规则中探讨了此主题。

我们将这种方法成功地使用Typescript。请注意,还可以为您的Mixin创建打字条定义文件,以便使用MixIn使用Mixin可以知道组件可以使用哪些Mixin方法/属性。我们当前针对Mixin通用类型的定义是在https://github.com/elix/elix/blob/master/src/src/shared.d.ts。

最新更新