Asaka
var XElementPrototype = Object.create(HTMLElement.prototype);
var XElement = document.registerElement('x-element', {
prototype: XElementPrototype
});
エレメント生成時、ノードへのアタッチ/削除時、属性変更時のコールバックを設定できる
var XElementPrototype = Object.create(HTMLElement.prototype);
// 生成時に呼ばれるコールバック
XElementPrototype.createdCallback = function(){
console.log("created");
};
var XElement = document.registerElement('x-element', {
prototype: XElementProtype
});
new XElement() // => "created"
描画されない不活性なテンプレート要素
HTMLElementとHTML+CSS+JSの間にShadowRootっていうやつを挟んでやると、影響をそのエレメント内に閉じることができる
+-> HTMLElement -> (HTML+CSS+JS) Document -| +-> HTMLElement -> ShadowRoot -> (HTML+CSS+JS)
var template = document.querySelector('#tmpl');
var div = document.querySelector('div');
var clone = document.importNode(template.content, true);
var shadowRoot = div.createShadowRoot();
shadowRoot.appendChild(clone);
<html>
<head>
<title>x-element</title>
<link rel='import' href='x-element.html'>
</head>
<body>
<x-element></x-element>
</body>
</html>
TemplateでCustom Elementの要素を作って、Shadow DOMで閉じてコンポーネント化し、importして使う
<!-- index.html -->
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>WebComponentsSample</title>
<link rel='import' href='x-element.html'>
</head>
<body>
<x-element></x-element>
</body>
</html>
<!-- x-element.html -->
<template id='tmpl'>
<style>
input, button {
border:1px solid #000;
border-radius: 3px;
}
</style>
<input type='text'>
<button>Button</button>
</template>
<script>
// importされるとdocumentはimport元のdocumentになるため自身のドキュメントを取得する
var importDoc = document.currentScript.ownerDocument;
var XElementPrototype = Object.create(HTMLElement.prototype);
XElementPrototype.createdCallback = function(){
console.log("created");
var template = importDoc.querySelector('#tmpl');
var clone = importDoc.importNode(template.content, true);
// x-elementのshadowRootを生成する
var shadowRoot = this.createShadowRoot();
shadowRoot.appendChild(clone);
};
var XElement = document.registerElement('x-element', {
prototype: XElementPrototype
});
</script>
自分でコンポーネント作るのちょっと面倒...
<link rel="import" href="bower_components/polymer/polymer.html">
<polymer-element name="x-element" noscript>
<template>
<style>
input, button {
border:1px solid #000;
border-radius: 3px;
}
</style>
<input type='text'>
<button>Button</button>
</template>
</polymer-element>
標準で動作する主要ブラウザは今のところchromeとopearaだけっぽい (polyfill使えばなんとか動くっぽいけど)