2017-12-09 15 views
0

ウェブコンポーネントのドラッグミックスを追加するためのtypescript mixinをビルドしています。これまではすべてがかなりうまくいった。しかし、ドラッグ可能なWebコンポーネントが切断された後にイベントリスナーを削除しようとすると、難しい問題が発生します。Webコンポーネントからイベントリスナーを削除する方法mixin - >プロパティ 'disconnectedCallback'がタイプ 'HTMLElement'に存在しません

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 
    } 
} 

メイン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にパッチを適用しますdisconnectedCallbacksuper.disconnectedCallbackはこのエラーに文句を言わないでしょう:Property 'disconnectedCallback' does not exist on type 'HTMLElement'。私はまだそれを試していない。これを修正するためのより良い方法はありますか?

+0

チップをありがとう。不幸にも、これはタイプスクリプトでは受け入れられません。両方の呼び出しで同じエラーが発生しました。 –

+0

おそらく;もしtypeof super.connectedCallback === 'function' ... – Supersharp

+0

私は 'super.connectedCallback'とタイプするとエラーが出ます。これは実行時エラーではなく、静的検査エラーです。 –

答えて

2

あなたのミックスインは、スーパークラスのメソッドの存在をテストすることができます。

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

ミックスインを多用して、このELIXプロジェクトは、そのcomposition rules for mixin methods and propertiesでこのトピックを探ります。

このアプローチは、TypeScriptで正常に使用できます。 TypeScriptがあなたのmixinを使ってコンポーネントに利用可能なmixinのメソッド/プロパティを知るように、あなたのmixin用のTypeScript定義ファイルを作成することも可能です。 Mixinジェネリックタイプの現在の定義はhttps://github.com/elix/elix/blob/master/src/shared.d.tsです。

+0

それは面白そうに見えますが、私はそれを試して答えに戻ります。ありがとうございました! –

関連する問題