0.3.0 • Published 10 months ago

mi-element v0.3.0

Weekly downloads
-
License
MIT
Repository
github
Last release
10 months ago

mi-element

a lightweight alternative to write web components

Only weights 2.3kB minified and gzipped.

mi-element provides features to build web applications through Web Components like:

  • type coercion with setAttribute
  • controllers to hook into the components lifecycle
  • ContextProvider, ContextConsumer for data provisioning from outside of a component
  • Store for managing shared state across components
  • Signal for reactive behavior

The motivation to build this module comes from the confusions around attributes and properties. "mi-element" solves this by providing the same results when setting objects or functions either through el.setAttribute(name, value) or properties el[name] = value.

Furthermore all observed attributes have a reactive behavior through the use of signals and effects. It implements signals (loosely) following the TC39 JavaScript Signals standard proposal.

Usage

In your project:

npm i mi-element
/** @file ./mi-counter.js */

import { MiElement, define, refsById, Signal } from 'mi-element'

// define your Component
class MiCounter extends MiElement {
  static template = `
  <style>
    :host { font-size: 1.25rem; }
  </style>
  <div id aria-label="Counter value">0</div>
  <button id="increment" aria-label="Increment counter"> + </button>
  `

  static get attributes() {
    // declare reactive attribute(s)
    return { count: 0 }
  }

  // called by connectedCallback()
  render() {
    // gather refs from template (here by id)
    this.refs = refsById(this.renderRoot)
    // apply event listeners
    this.refs.increment.addEventListener('click', () => {
      // change observed and reactive attribute...
      this.count++
    })
    Signal.effect(() => {
      // ...triggers update on every change of `this.count`
      this.refs.div.textContent = this.count
    })
  }
}

// create the custom element
define('mi-counter', MiCounter)

Now use your now component in your HTML

<body>
  <mi-counter></mi-counter>
  <mi-counter count="-3"></mi-counter>
  <script type="module" src="./mi-counter.js"></script>
</body>

In ./example you'll find a working sample of a Todo App. Check it out with npm run example

Documentation

License

MIT licensed

0.1.0

11 months ago

0.3.0

10 months ago

0.2.0

11 months ago

0.0.1

11 months ago