Reputation: 4655
I'm working with Web Components and try to bind a click
event to an element inside of the Shadow DOM.
1. component.html included as <link rel="import" ...>
inside of index.html
<template id="my-element">
<section>
<header>
<content select="h1"></content>
<button></button>
</header>
<content select="div"></content>
</section>
</template>
2. later element usage:
<my-element>
<h1>Headline</h1>
<div>...</div>
</my-element>
3. Access element and bind a function to it
Now I want to add an addEventListener()
to the <button>
inside of my <my-element>
(which is unfortunately hidden through the #shadow-root
). Like:
var elemBtn = document.querySelector('my-element button');
elemBtn.addEventListener('click', function(event) {
// do stuff
});
But that won't work. How do I achieve that?
Upvotes: 1
Views: 2729
Reputation: 6786
You should be able to do this without involving the window object. Here's a full example:
<!-- Define element template -->
<template>
<h1>Hello World</h1>
<button id="btn">Click me</button>
</template>
<!-- Create custom element definition -->
<script>
var tmpl = document.querySelector('template');
var WidgetProto = Object.create(HTMLElement.prototype);
WidgetProto.createdCallback = function() {
var root = this.createShadowRoot();
root.appendChild(document.importNode(tmpl.content, true));
// Grab a reference to the button in the shadow root
var btn = root.querySelector('#btn');
// Handle the button's click event
btn.addEventListener('click', this.fireBtn.bind(this));
};
// Dispatch a custom event when the button is clicked
WidgetProto.fireBtn = function() {
this.dispatchEvent(new Event('btn-clicked'));
};
var Widget = document.registerElement('my-widget', {
prototype: WidgetProto
});
</script>
<!-- Use the element -->
<my-widget></my-widget>
<!-- Listen for its click event -->
<script>
var widget = document.querySelector('my-widget');
widget.addEventListener('btn-clicked', function() {
alert('the button was clicked');
});
</script>
Upvotes: 5
Reputation: 4655
I found out that creating a custom createEvent('MouseEvent');
inside of <template>
will do the trick!
TL;DR http://jsfiddle.net/morkro/z0vbh11v/
1. First, you need to add the onclick=""
-attribute to our <template>
and create a custom event:
<template id="my-element">
<section>
<header>
<content select="h1"></content>
<button onclick="callEventOnBtn()"></button>
</header>
<content select="div"></content>
</section>
<script>
var btnEvent = document.createEvent('MouseEvent');
btnEvent.initEvent('oncomponentbtn', true, true);
var callEventOnBtn = function() {
window.dispatchEvent(btnEvent);
};
</script>
</template>
I create the custom event inside of the <template>
and automatically dispatch it to the global window
object when the Custom Element gets used later.
2. Now we can listen to that event, when clicking the <button>
on our custom element
window.addEventListener('oncomponentbtn', function(event) {
// do stuff
});
Upvotes: 0