Web コンポーネント (バニラ) を使い始めたばかりで、ユーザーがコンポーネントに対してプログラムでアクションを実行できるようにしたいと考えています (たとえば、「コンポーネントを左にスライド」)。
コンポーネントでイベントをディスパッチ/トリガーし、コンポーネントにこれらのイベントをリッスンさせることを考えていました(より良い方法があれば修正してください)。
<custom-element>
// ...
</custom-element>
var customElement = document.querySelector('.custom-element');
customElement.dispatchEvent(new Event('slideLeft'));
<custom-element>
次に、コンポーネントでこれを聞くことができるようにする必要があります..しかし、ここの要素にアクセスする方法がわかりません。
// Gets a handle to this import doc.
var importDoc = document.currentScript.ownerDocument;
// Creates an object based in the HTML Element prototype.
var element = Object.create(HTMLElement.prototype);
// Fires when an instance of the element is created.
element.createdCallback = function () {
// Create a shadow root.
var shadow = this.createShadowRoot();
// Get a reference to the template.
var template = importDoc.querySelector('#custom-element-tpl');
// Append a deep clone of the template into the shadow.
shadow.appendChild(template.content.cloneNode(true));
};
document.registerElement('custom-element', {
prototype: element
});
ありがとう。