什么是 ES205 / JS6 方式,制作一个与 DartLang 制作的自定义元素等效的自定义元素
问问题
843 次
1 回答
1
我能够做到,以下是我为有兴趣的人所做的:
"use strict";
// DART: class SaveBtn extends HtmlElement { static final tag = 'save-button';
// ES2015 / JS6
class SaveBtn extends HTMLElement {
// DART: factory SaveBtn([String name]) => (new Element.tag(tag) as SaveBtn)..name = name;
// ES2015 / JS6
constructor() {
super();
}
// DART: SaveBtn.created() : super.created() {
// ES2015 / JS6
createdCallback(){
// Create a Shadow Root, DART & ES2015
var shadow = this.createShadowRoot();
// Create a standard element and set it's attributes.
// DART: innerButton = new ButtonElement()..id='btn';
// ES2015 / JS6
var innerButton = document.createElement('button');
innerButton.id='btn';
innerButton.addEventListener('click',() => console.log('The button had been clicked'));
shadow.appendChild(innerButton);
}
// DART: void attached() { }
// ES2015 / JS6
attachedCallback(){
console.log(this.dataset);
console.log(this.textContent);
this.shadowRoot.querySelector('#btn').textContent = this.textContent != '' ? this.textContent : this.dataset['text'];
}
detachedCallback(){
}
attributeChangedCallback(textContent) {
}
set text(v) {
this.textContent = v;
}
get text() {
return this.textContent;
}
}
var MySaveBtn = document.registerElement("save-button", SaveBtn);
var x = new MySaveBtn;
x.text = 'test';
console.log(x.text);
document.querySelector('#placeholder').appendChild(x);
我使用的 HTML 文件是:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ES2015 / JS6 Custom Elements</title>
<script src="default.js" type="text/javascript"></script>
</head>
<body>
Here is some non-custom stuff.
<div id="placeholder"><p>Please wait, loading cool things<p></div>
<save-button data-text='click this'></save-button>
</body>
</html>
在不使用 SHADOWROOT 的情况下解决它的另一种方法是在这里
于 2015-11-27T20:55:22.507 回答