1

私は Web コンポーネントを扱っておりclick、Shadow DOM 内の要素にイベントをバインドしようとしています。

1. <link rel="import" ...>index.html の内部に含まれる component.html

<template id="my-element">
    <section>
        <header>
            <content select="h1"></content>
            <button></button>
        </header>
        <content select="div"></content>
    </section>
</template>

2. その後の要素の使用法:

<my-element>
    <h1>Headline</h1>
    <div>...</div>
</my-element>

3. 要素にアクセスし、関数をバインドします

ここで、 myの内部にを追加したいと思います(残念ながら によって隠されています)。お気に入り:addEventListener()<button><my-element> #shadow-root

var elemBtn = document.querySelector('my-element button');
elemBtn.addEventListener('click', function(event) {
    // do stuff
});

しかし、それはうまくいきません。どうすればそれを達成できますか?

4

2 に答える 2

5

これは、window オブジェクトを使用せずに実行できるはずです。完全な例を次に示します。

<!-- 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>

jsbin での例

于 2015-02-06T18:23:57.420 に答える
0

createEvent('MouseEvent');内部でカスタムを作成するとうまくいくことがわかりました<template>

TL;DR http://jsfiddle.net/morkro/z0vbh11v/


1. まず、onclick=""-attribute を追加し<template>て、カスタム イベントを作成する必要があります。

<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>

の内部でカスタム イベントを作成し、カスタム要素が後で使用されるときに<template>グローバル オブジェクトに自動的にディスパッチします。window

<button>2.カスタム要素をクリックすると、そのイベントをリッスンできます

window.addEventListener('oncomponentbtn', function(event) {
    // do stuff
});
于 2015-02-05T23:48:50.237 に答える