2017-12-09 3 views
0

드래그 동작을 추가하기 위해 웹 구성 요소의 타이프 스크립트 믹스를 작성 중입니다. 지금까지 모든 것이 꽤 잘 작동했습니다. 그러나 draggable 웹 구성 요소가 분리 된 후 이벤트 수신기를 제거하려고하면 어려운 문제가 발생합니다.웹 구성 요소에서 이벤트 수신기를 제거하는 방법 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)) 

내가 지금까지 가지고있는 유일한 생각은 원숭이가 disconnectedCallback 더미를 포함하도록 HTMLElement에 패치를 적용하면 super.disconnectedCallbackProperty 'disconnectedCallback' does not exist on type 'HTMLElement'이라는 오류를 표시하지 않습니다. 나는 아직 그것을 시도하지 않았다. 이 문제를 해결할 수있는 더 좋은 방법이 있습니까?

+0

팁 주셔서 감사합니다. Unfortunatelly 이것은 다시 typescript에 의해 받아 들여지지 않습니다. 두 호출 모두 동일한 오류. –

+0

아마도; 만약 typeof super.connectedCallback === 'function'... – Supersharp

+0

'super.connectedCallback'이라고 입력하면 오류가 발생합니다. 이는 런타임 오류가 아니라 정적 검사 오류입니다. –

답변

2

귀하의 믹스 인은 슈퍼 클래스의 메소드의 존재를 테스트 할 수 있습니다

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

유지 mixin 많이 사용한다이 Elix 프로젝트는 그 composition rules for mixin methods and properties에서이 주제를 탐구한다.

이 접근 방식은 TypeScript에서 성공적으로 사용됩니다. TypeScript가 믹스 인을 사용하는 컴포넌트에서 사용할 수있는 믹스 인 메서드/속성을 알 수 있도록 믹스 인에 대한 TypeScript 정의 파일을 만들 수도 있습니다. Mixin 제네릭 유형의 현재 정의는 https://github.com/elix/elix/blob/master/src/shared.d.ts입니다.

+0

재미있을 것 같아서 테스트 해보고 대답하겠습니다. 고맙습니다! –

관련 문제