Search code examples
javascriptweb-componentevent-dispatching

Access Web Component element from itself


Just started playing with Web Components (vanilla) and I would like the user to be able to programmatically perform actions on the component (e.g. "slide component left").

I was thinking (correct me if there is a better way) to dispatch/trigger events on the component and have the component listen for these events.

<custom-element>
    // ...
</custom-element>

var customElement = document.querySelector('.custom-element');
customElement.dispatchEvent(new Event('slideLeft'));

Then in the component I need to be able to listen to this.. But I don't know how to access the <custom-element> element here.

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

Thanks.


Solution

  • Ok this was kinda obvious when I thought about it but leaving here for reference:

    You can access the current element using the this context inside the createdCallback.. which is what the createShadowRoot is called on.

    // Fires when an instance of the element is created.
    element.createdCallback = function () {
        // this = <custom-element></custom-element>
        this.addEventListener(...);
    });