Polight / lego

🚀 Low-Tech Web-Components Made Lightweight & Future-Proof.
https://lego.js.org
MIT License
118 stars 19 forks source link

Allow access to specific variables/functions #40

Open vinyll opened 1 year ago

vinyll commented 1 year ago

A real world usecase requires to access the document, as for collecting data from a form (ex: document.querySelector('a')).

Right now document can't be accessed outside of the component class and we must still extend the Lego class to use it. We may want to consider to make the document variable accessible.

Same issue with the component itself. I do have a case where the component itself, as a dom element, has to modify its classList from within the component. Using the Lego class it's as easy as this.classList but in the new version this is undefined. We may want to consider to make the component available to the script like with a reference to it such as self, node, component or another name.

This will lead to a reserved words list that must be listed in the doc. Currently the only reserved words are state and render. We could either extend the list, or only add a reference to the component and call methods or properties from there.

We need to decide:

vinyll commented 1 year ago

A solution was implemented:

<script>
  const state = {name: 'bob'}

  // `constructed` is called when the component is fully ready (state and attributes are loaded, dom is rendered)
  // `this` refers to the component itself and gives access to the whole context.
  function constructed() {
    console.info(`The component ${this.nodeName} is now ready`)
  }
</script>

It would result with the following reserved words: