0

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
});

ありがとう。

4

1 に答える 1

1

わかりました、これは私がそれについて考えたときにちょっと明白でしたが、参考のためにここに残しておきます:

..this内のコンテキストを使用して、現在の要素にアクセスできます。これは、呼び出されたものです。createdCallbackcreateShadowRoot

// Fires when an instance of the element is created.
element.createdCallback = function () {
    // this = <custom-element></custom-element>
    this.addEventListener(...);
});
于 2014-08-24T00:33:48.093 に答える