html5で追加Custom ElementsとHtml TemplateとShadow DOMとHTML Importsにめっちゃ期待してるけど複雑怪奇なので全部使ったページを作ってみた。はよIE対応はよはよはよ。chrome最新版で動作確認。 chsh-index HTML Importsがあるから2つのファイルに分かれている。たぶんこれで全部の機能が理解できます。shadowRootのインスタンスをどこに保存するか、どうやって取得するのかで若干悩んだ。多分もっとスマートな書き方あるはず。 Custom Elements→document.registerElement('x-test',{prototype:proto}); Html Template→chsh-template.htmlDefault <template id="cells-to-repeat"> Shadow DOM→var shadowRoot=this.createShadowRoot(); HTML Imports→<link rel="import" href="chsh-template.html" id="linkNode1"> ソースはこんな感じ。
<template id="cells-to-repeat"> <style> label{ background-color:cyan; } </style> <label><button id="push">ボタン押して数が増える→</button><span id="count">000</span></label> </template>
<link rel="import" href="chsh-template.html" id="linkNode1"> <script> br=function(){return document.createElement("br");}; nodes=[]; window.addEventListener("DOMContentLoaded", function(){ document.querySelector("#total").addEventListener("click",getAllNumber); xtest=(function(){ var proto=Object.create(HTMLElement.prototype, { createdCallback: { value: function() { var tempNode = document.querySelector('#linkNode1').import; var t = tempNode.querySelector('template'); var clone = document.importNode(t.content, true); var shadowRoot=this.createShadowRoot(); shadowRoot.appendChild(clone); this.doc=shadowRoot; this.number=0; } }, attachedCallback : { value: function(){ //buttonにイベントをセットする var base=this; this.shadowRoot.querySelector("#push").addEventListener("click",function(){ base.number++; base.doc.querySelector("#count").innerText=base.number; }); } }, attributeChangedCallback : { value: function(attrName, oldVal, newVal){ } }, detachedCallback : { value: function(){ } }, }); return document.registerElement('x-test',{prototype:proto}); })(); newCreate(); newCreate(); newCreate(); }, false); function newCreate(){ var addNew=new xtest(); nodes.push(addNew); document.body.appendChild(addNew); document.body.appendChild(br()); } function getAllNumber(){ var total=0; for(var i=0;i<nodes.length;i++){ total+=nodes[i].number; } alert(total); } </script> <button id="total">合計数</button> <hr>