The behavior feature

Syntax

behavior <name>(<parameter list>)
  {<hyperscript>}
end
install <name>(<named argument list>)

Description

Behaviors allow you to bundle together some hyperscript code (that would normally go in the _ attribute of an element) so that it can be "installed" on any other.

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ā„¢. 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ā„¢ innovation is reusable!

For a more realistic example of a behavior, check out the Draggable behavior which creates a draggable window: Draggable._hs

Ordering

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>