6

2つのカスタム要素(v1)を持つWebコンポーネントを使用して簡単な例を作成しました。 のindex.html:ネストされた要素(Webコンポーネント)がテンプレートを取得できません

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <title>Example</title> 
    <meta name="description" content=""> 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
    <link rel="import" href="app-container.html"> 
</head> 
<body> 
    <app-container></app-container> 
</body> 
</html> 

アプリ-container.html:

<link rel="import" href="toolbar.html"> 
<template id="app-container"> 
    <app-toolbar></app-toolbar> 
</template> 
<script> 
    customElements.define('app-container', class extends HTMLElement { 
    constructor() { 
     super(); 
     let shadowRoot = this.attachShadow({ mode: 'open' }); 
     const content = document.currentScript.ownerDocument.querySelector('#app-container').content; 
     shadowRoot.appendChild(content.cloneNode(true)); 
    } 
    }); 
</script> 

toolbar.html:

しかしtoolbar.html document.currentScriptでは、アプリと同じです-container.htmlとなるため、のテンプレートが見つかりません。querySelector('#app-toolbar')この問題を解決するには?

クロム55(polyfillなし)でテストされた例。

答えて

13

document.currentScriptには、現在解析され実行されているスクリプトへの参照が含まれています。したがって、constructor()関数が(他のスクリプトから)呼び出されたときに、あなたの目的にはもう有効ではありません。

代わりに、あなたは、スクリプトの先頭で変数にその値を保存し、コンストラクタでこの変数を使用shoud:

<script> 
    var currentScript = document.currentScript 
    customElements.define(...) 
    ... 
</script> 

あなたは複数のスクリプトを持っている場合、あなたは明確な名前を使用する必要があります。

代わりに、あなたが閉鎖にはかない値をカプセル化することができます

ここ
(function(owner) { 
    customElements.define('app-container', class extends HTMLElement { 
     constructor() { 
      super(); 
      let shadowRoot = this.attachShadow({ mode: 'open' }); 
      const content = owner.querySelector('#app-container').content; 
      shadowRoot.appendChild(content.cloneNode(true)); 
     } 
    }); 
})(document.currentScript.ownerDocument); 

document.currentScript.ownerDocumentconstructor()が呼び出されたときに、まだ正しく定義されているowner引数に割り当てられています。

ownerはローカルで定義されているため、他のドキュメントで同じ名前を使用できます。

+0

スーパーシャープ、多くのありがとう!明けましておめでとうございます! –

+0

ありがとう、あなたも! – Supersharp

関連する問題