behavior FeatureBehaviors let you bundle hyperscript code into a reusable unit that can be "installed" on any element. Think of them as mixins for DOM elements -- you define the behavior once, then install it wherever you need it.
For instance, consider this disappearing div:
<div
_="
on click remove me
"
>
Click to get rid of me
</div>
This revolutionary UI technology impresses the client, and they come to you with a list of other components that they would like to be Removable(tm). Do you copy this code to each of those elements? That would work, but is not ideal, since
To remedy this, you can define a behavior:
<script type="text/hyperscript">
behavior Removable
on click
remove me
end
end
</script>
and install it in your elements:
<div _="install Removable">Click to get rid of me</div>
So far, so good! Until you come across this:
<div class="banner">
<button id="close-banner"></button>
Click the button to close me
</div>
How do we implement this? We could create a new behavior, but we'd have to duplicate our highly sophisticated logic. Thankfully, behaviors can accept arguments:
<script type="text/hyperscript">
behavior Removable(removeButton)
on click from removeButton
remove me
end
end
</script>
<div class="banner" _="install Removable(removeButton: #close-banner)">...</div>
This works well, but now our original div is broken. We can use an init block to set a default value for the parameter:
<script type="text/hyperscript">
behavior Removable(removeButton)
init
if no removeButton set the removeButton to me
end
on click from removeButton
remove me
end
end
</script>
Now our Removable(tm) innovation is reusable!
For a more realistic example of a behavior, check out the Draggable behavior which creates a draggable window: Draggable._hs
Behaviors must be defined before they are "installed," if defined locally. If behaviors are loaded remotely this has to be done before loading hyperscript.
<script type="text/hyperscript" src="/behaviors._hs"></script>
<script src="https://unpkg.com/hyperscript.org"></script>
behavior <name>(<parameter-list>)
<feature>+
end
install <name>(<named-argument-list>)