2

두 개의 사용자 정의 요소를 생성하고 있으며, 둘 다 link rel = "import"를 사용하여 index.html에 추가됩니다. 하나는 슬롯이있는 컨테이너이고 다른 하나는 슬롯에 숫자를 넣는 것입니다. 두 요소는 각각 템플리트가있는 HTML 파일과이를 사용자 정의 요소로 정의하는 js 파일에 대한 링크가 있습니다. 내가 사용하고있는 HTML 템플릿에 사용자 정의 요소 클래스 선언을 연결하려면 :사용자 정의 요소의 createElement가 템플릿을 손상합니다.

class PuzzlePiece extends HTMLElement{ 

constructor(){ 
    super(); 
    console.dir(document.currentScript); 
    const t = document.currentScript.ownerDocument.getElementById('piece-puzzle'); 
    const shadowRoot = this.attachShadow({mode: 'open'}); 
    shadowRoot.appendChild(t.content.cloneNode(true)); 
} 

이 퍼즐 조각 요소와 컨테이너가 제대로 렌더링 및 모든 작품을하는 것은 수동으로 index.html을 빛의 DOM에 넣어 때

그러나
<special-puzzle id="grid"> 
    <puzzle-piece id="hello"></puzzle-piece> 
</special-puzzle> 

, 나는 시도하고 index.html을에 JS를 사용하여 퍼즐 조각을 만들고 추가하면 :

<script> 
    const addToGrid = document.createElement("puzzle-piece"); 
    document.getElementById("grid").appendChild(addToGrid); 
</script> 

내가 특별한 퍼즐 빛 DOM에 새로운 퍼즐 조각을 볼 수 있지만 그것을 슬롯을 차지하지 않는, 렌더링, 콘솔 오류가 없습니다 : 브라우저가 클래스에 점점 document.createElement를 사용하는 경우 지금까지 내가 문제를 말할 수있는

Uncaught TypeError: Cannot read property 'content' of null at new PuzzlePiece (puzzle-piece.ts:8) at HTMLDocument.createElement (:3:492) at (index):37

입니다 정의하지만, document.currentScript.ownerDocument는 HTML 태그를 수동으로 사용하는 경우와 다릅니다. 이 때문에 구성 요소가 템플릿을 찾을 수 없다고 생각합니다. 이것은 내 첫 번째 스택 오버 플로우 질문이므로 모든 의견/도움을 주시면 감사하겠습니다!

+0

가 [GitHub의]의 코드 (https://github.com/arjunyel/special-puzzle) –

+2

이 한 번 봐 답변 : http://stackoverflow.com/a/42093412/4600982 – Supersharp

+2

또는이 하나 : http://stackoverflow.com/a/41409299/4600982 – Supersharp

답변

2

해결 멋진 @Supersharp 덕분에 그들의 Stack Overflow post

기본적으로,이 클래스는 다음 수업 시간에 그 VAR를 사용하기 전에 var에 그것을 선언해야 올바른 document.currentScript.ownerDocument을 보존하기 위해있다.

올드 :

class PuzzlePiece extends HTMLElement{ 
constructor(){ 
super(); 
const t = document.currentScript.ownerDocument.getElementById('piece-puzzle'); 
const shadowRoot = this.attachShadow({mode: 'open'}); 
shadowRoot.appendChild(t.content.cloneNode(true));} 

새로운 기능 : 여기

var importedDoc = document.currentScript.ownerDocument; 
class PuzzlePiece extends HTMLElement{ 
constructor(){ 
super(); 
const t = importedDoc.getElementById('piece-puzzle'); 
const shadowRoot = this.attachShadow({mode: 'open'}); 
shadowRoot.appendChild(t.content.cloneNode(true));}