Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

251
Visualizações
How does a child element access custom web component class functions and vars?

Within a custom component defined with <template> and <slot> tags, a child element can get the parent element that is the custom component, and then use this element reference to access class defined vars and functions.

However, how can a child element know which element is the custom component?

The template itself is contained in a shadow DOM. When rendering a custom component on the page, this shadow DOM is cloned and attached into the custom component as its host.

Elements that are slotted in to the custom component however can't seem to tell the node tree it is attached to came from a shadow DOM node that was cloned, and can't tell which element in the current DOM tree is the top level custom component unless it iterates through each parentNode to check if they have a shadowRoot.

What is the way to let a child element inside a custom component access the custom component's class variables and functions?

customElements.define("my-comp", class extends HTMLElement {
  creationTimestamp;

  constructor() {
    super();
    let template = document.getElementById('my-template');
    let templateContent = template.content;

    const shadowRoot = this.attachShadow({
      mode: 'open'
    });
    shadowRoot.appendChild(templateContent.cloneNode(true));

    this.creationTimestamp = Date.now();
  }
})
<html>

<template id="my-template">
  I'm a new custom component using slots with value <slot name="slot1">default</slot>
  <button onclick="console.log(this.parentNode.host.creationTimestamp)">Print timestamp at Template level</button>
</template>

<my-comp>
  <span slot="slot1">
    slotted value
    <div>
      <button onclick="console.log(this.parentNode.parentNode.parentNode.creationTimestamp)">Print timestamp</button>
    </div>
  </span>

</my-comp>

</html>

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Now I understand. You want to prevent:

let timeStamp = this.parentNode.parentNode.parentNode.creationTimestamp;

There are multiple StackOverflow answers tackling this:

  1. Let the child find a parent
    In control: child
    mimic standard JS .closest(selector) which does not pierce shadowRoots!
    with a custom closestElement(selector) function:
    Custom Element getRootNode.closest() function crossing multiple (parent) shadowDOM boundaries

  2. Make the parent tell something to a child
    In control: parent
    by a recursive dive into shadowRoots:
    How can I get all the HTML in a document or node containing shadowRoot elements

  3. Let the parent respond to a call from a child
    In control: both Child sends Event, Parent needs to listen
    Webcomponents communicating by custom events cannot send data

about 4 years ago · Juan Pablo Isaza Relatório

0

The simple rules I use for decoupling are:

  • Parent to child: one-way data-binding or HTML5 attributes for passing data and calling child.func() for performing actions.

  • Child to parent: Child fires an event. The parent(s) listen for that event. Because of event bubbling you can have an arbitrary number of parents picking up that event with no extra effort.

This pattern is used by standard web components as well (input, textbox etc). It also allows easy testing since you don't have to mock the parent.

This was the recommended pattern described by the Polymer library, which was/is a wrapper over WebComponents. Unfortunately I can't find that specific article that described this pattern.

polymer element communication diagram

In the following example, the parent listens for events from children and calls functions on itself to affect its state, or functions on the children to make them do something. None of the children know about the parent.

Diagram showing parent listening for child events and performing actions on itself or calling

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda