Polight / lego

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

cutom events #27

Open echb opened 2 years ago

echb commented 2 years ago

i've tried use custom events and i failed forthright, someone has used lego with custom events?

vinyll commented 2 years ago

Hey @echb! Because Lego is native HTML/JS, I'm pretty sure CustomEvent should work out of the box. Do you have a piece of code to share your context?

vinyll commented 2 years ago

The 3rd block at https://polight.github.io/lego-demo/ will show you a demo of a webcomponent updated from a CustomEvent, that's the most simplistic version. The source of that component is here: https://github.com/Polight/lego-demo/blob/main/bricks/customevent-clock.html

echb commented 2 years ago

The component code

<template>
  <div class="container" @click="test">
    <div class="container">
      <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Aspernatur ut quos error totam reprehenderit fuga
        aperiam, explicabo quisquam, architecto at cumque assumenda illum corrupti natus facilis quasi, doloribus
        laborum
        odio.</p>
    </div>
</template>

<script>
  export default class extends Lego {

    connected() {
    }

    init() {
      this.state = {
      }

    }
    test() {
      const MessageEvent = new CustomEvent("message", {
        detail: { from: "Manz", message: "Hello!" },
        bubbles: true,
        composed: true
      });
      this.dispatchEvent(MessageEvent);
    }
  }
</script>

<style>
  .container {
    display: inline-flex;
    background-color: #9f1717;
    color: antiquewhite;
    padding: 2px 5px 2px 5px;
    border-radius: 10px;
  }

  ::slotted(*) {
    display: inline-block;
    /* background-color: green; */
    border: none;
    margin: 0;
    padding: 0;
  }
</style>

This is script calling outside component

  const prop = document.querySelector('lego-prop')
  prop.addEventListener('message', (e) => {
    console.log(e);
  })

The problem comes whe nest components

<template>
  <div class="container">
    <p>component with nested one</p>
    <div class="container">
      <lego-prop @message="test"></lego-prop>
    </div>
</template>

<script>
  export default class extends Lego {

    connected() {
      console.log('asd');
    }

    init() {
      this.state = {
      }

    }
    test(e) {
      console.log(e);
    }
  }
</script>
vinyll commented 2 years ago

Hey @echb! I'll set this up in the demo eventually and we can have a look together to get this running as expected. We could ensure it works as basic HTML elements with the custom event as you are using it as a POC and then investigate what the issue is in this specific case. I should find some time to get into it this week.

I'm pretty confident we should work this out :)