Custom Plugin

Demo

Explanation #

Custom actions, attributes, and watchers can be implemented using the plugin API. This example implements a simple alert action and attribute.

Action #

An action plugin can be implemented as follows.

1action({
2    name: 'alert',
3    apply(ctx, value) {
4        alert(value)
5    }
6})

Setting the name to alert results in the syntax @alert.

1<button data-on:click="@alert('Hello from an action')">
2    Alert using an action
3</button>

Attribute #

An attribute plugin can be implemented as follows.

 1attribute({
 2    name: 'alert',
 3    requirement: {
 4        key: 'denied',
 5        value: 'must',
 6    },
 7    returnsValue: true,
 8    apply({ el, rx }) {
 9        const callback = () => alert(rx())
10        el.addEventListener('click', callback)
11        return () => el.removeEventListener('click', callback)
12    }
13})

Setting the name to alert results in the syntax data-alert.

The attribute shouldn’t take a key and needs a value, so key is denied and value is a must. The attribute expects a value to be returned from the expression so we set returnsValue to true.

On apply, we create an event listener that alerts the value returned from the expression when the element is clicked. We return a function that removes the event listener on cleanup.

1<button data-alert="'Hello from an attribute'">
2    Alert using an attribute
3</button>