ChocoBase

This is the main class most building blocks and headless classes inherits from. It sets the stage for the choco action by enforcing a simple contract with just attributes and actions, as well as two additional methods for extending these.

The constructor accepts an optional record of HTML attributes and a type parameter allows to constrain the class to be used on specific HTML tags.


Example

The ChocoBase class defines two methods, extendAttributes and extendActions which allow to specialize the attributes and behavior of the class at any point in the future. This is useful for creating specialized building blocks or headless classes.


<script lang="ts">
  import { ChocoBase } from "chocobytes/blocks/base.svelte.js";
  import { addListener } from "chocobytes/actions/addListener.js";
  import { choco } from "chocobytes/index.js";

  // Here we constrain `base` to be used on buttons only
  const base = new ChocoBase<"button">({ disabled: false, value: "ok" });

  // Subclasses of `ChocoBase` can add aria attributes in this way
  base.extendAttributes({
    "data-my-attribute": "custom",
  });

  // Subclasses of `ChocoBase` can add specialized behavior
  base.extendActions((node) => console.log("hello", node));

  // `addListener` is a convenient helper to create an action from a listener
  // with cleanup managed automatically
  base.extendActions(addListener("click", () => console.log("click")));
</script>

<button class="py-2 px-4 outline" use:choco={base}>Click and check console</button>

<pre>{JSON.stringify(base.attributes, null, 2)}</pre>


API

Below, T refers to the type the ChocoBase<T> class was constrained to. By default it is set to "generic", which implies the available attributes are those of a generic HTMLElement.

attributes: Attributes<T>
A getter returning the attributes. Used internally by the preprocessor
action: Action<HTMLElementsMap[T]>
A getter merging all defined actions into a single one. Used internally by the preprocessor
extendAttributes: (newAttributes: Attributes<T>): void
A method allowing to add or override attributes.
extendActions: (...actions: Action<HTMLElementsMap[T]>[]): void
A method allowing to add new behavior with actions.