Your own elements
When the built-in elements don't fit, write your own. Extend TangleElement, the class the
built-in elements extend, and register it with customElements.define. Your element then works
with the same variables, scopes and expressions as <t-num> and <t-out>.
A bar that shows a value
The smallest element reads variables and draws. Here, <t-bar> fills up to the value of its
expr, from 0 to 1:
Saving
this.watch(fn) is the same as scope.effect(fn): fn gets the
element's scope, and s.get and s.eval subscribe to what they read. The difference is that
it stops when the element leaves the page.
A slider that sets a variable
An element can declare a variable and set it. <t-slider> wraps a range input. It's bound to the
same speed as the <t-num>, so moving either one moves the other:
Driving at
this.declare(name, initial) sets the variable's settings from the element's attributes, and
its value if nothing has set it yet. s.meta(name) reads those settings back, whichever element
declared them.
A draggable of your own
this.makeDraggable(name) makes an element behave like a <t-num>: the reader can
drag it, click to type, or use the arrow keys, hovering highlights every other
place the variable appears, and screen readers announce it as a slider. You only decide how it
looks:
A draggable gets the same color, hover and focus styles as a <t-num>, from
[data-tangle-param] in tangle.css. Its color attribute works too. See
Styling.
Reference
| Member | Description |
|---|---|
this.scope | The element's scope: its nearest <t-scope>, or the page-wide one. |
this.watch(fn) | Runs fn(scope) now, and again whenever a variable it read changes. Stops when the element is removed. While a variable it read is reloading, the element has the class is-stale. |
this.declare(name, initial) | Declares name from the min, max, step, color, label and format attributes, and sets it to initial unless something already did. |
this.makeDraggable(name, target) | Lets the reader drag, type or arrow-key name on target, which defaults to the element itself. |
A few things to keep in mind:
- Put setup in
connectedCallback. It runs when the element is added to the page, and again if it's moved.watcheffects stop when it's removed. If you overridedisconnectedCallback, callsuper.disconnectedCallback(). - Pick a name that won't clash. Any name with a hyphen works. A future version may add more
t-elements, so a prefix of your own, likemy-bar, is safest. - Import from the same URL as the
<script>tag that loadstangle.js, or your element gets a separate copy with separate variables. See Importing. - Define elements in one file. On a blog, put them in a module such as
elements.jsand load it on every page, aftertangle.js. Elements already in the page upgrade when they're defined, so it doesn't matter whether the script runs before or after the content.