Skip to content

Support named export (top-level binding) #63

@DrSensor

Description

@DrSensor

Warning: this pattern is highly experimental

<render-scope>
  <link top-level href=module.js>
  <template shadowrootmode=closed>
    <button :=counter>0</button>
    <span :: text:=set:total>0</span>
  </template>
</render-scope>
function increment() { this.value++ }

export function counter(element) {
  element ??= this ?? <button/>
  element.addEventListener("click",  increment)
  return element
}

👣 Footgun: how do you bind variable (i.e total)?

export let total
// total += 1
// require compiler
// (maybe compile to class
//  with @bind accessor
//  for the sake of performance
//  😂)

export const total = {}
// total.value += 1
// works without compiler but weird

The reason I'm interested in named export is because of handleEvent() pattern in class1

<render-scope>
  <link top-level href=module.js>
  <template shadowrootmode=closed>
    <button :=Counter>0</button>
  </template>
</render-scope>
export class Counter {
  value = 0
  constructor(element = <button/>) {
    element.addEventListener("click",  this)
    return Object.setPrototypeOf(element, new.target.prototype)
  }
  handleEvent(event) {
    switch (event.type) {
      case "click":
        this.increment()
        break
      default:
        this.value = +event.currentTarget.value
    }
  }
  increment() { this.value++ }
}

use module in other area or projects

import { Counter } from "./module.js"
for (const input of document.querySelectorAll("input.counter")) {
  const counter = new Counter()
  input.after(counter)
  input.addEventListener("change", counter)
}

Footnotes

  1. DOM handleEvent: a cross-platform standard since year 2000

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requestexperimentalBreaking changes can happen at any time

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions