在开始使用Polymer之前,我开始详细了解Web组件 .
我正在研究一个使用两个 <button>
和一个 <input type="text">
元素创建旋转按钮的简单示例 .
模板是:
<template id="tplSpinButton">
<style type="text/css">
.spin-button > * {
display: inline;
text-align: center;
margin: 0;
float: left;
}
</style>
<div class="spin-button">
<content select=".up-spin-button"></content>
<content select=".display-spin-button"></content>
<content select=".down-spin-button"></content>
</div>
</template>
主机元素如下:
<article>
<spin-button>
<button class="up-spin-button">+</button>
<input class="display-spin-button" type="text" value="0" size="2"/>
<button class="down-spin-button">-</button>
</spin-button>
</article>
和JS代码
var template = document.querySelector('#tplSpinButton');
var host = document.querySelector('article spin-button');
var articleShadowRoot = host.createShadowRoot();
articleShadowRoot.appendChild(document.importNode(template.content,true));
var counterBox = document.querySelector('.display-spin-button');
var upHandler = document.querySelector('.up-spin-button');
var downHandler = document.querySelector('.down-spin-button');
upHandler.addEventListener('click', function(e){
var count = parseInt(counterBox.value);
counterBox.value = count + 1;
}, false);
downHandler.addEventListener('click', function(e){
var count = parseInt(counterBox.value);
counterBox.value = count - 1;
}, false);
document.registerElement('spin-button', {
prototype: Object.create(HTMLElement.prototype)
});
在实验期间,我发现JS /代码不起作用 <style>
做阴影DOM是 <template>
的一部分在上面的例子中我添加了插入点( <content>
),然后将事件监听器附加到分布式元素 .
-
Is there any way to encapsulate the event listener implementation?
-
Is there any way to move the controls s and elements to shadow dom and then attaching event listener by any way?
1 回答
您可以将其作为元素原型的一部分并在lifecycle callback中构建它 .
使用getDistributedNodes选择要投影到内容标记中的元素 .
这是a jsbin,它说明了这两个概念 . 希望有所帮助!