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:

behavior Removable
  on click
    remove me
  end
end

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:

behavior Removable(removeButton)
  on click from removeButton
    remove me
  end
end
<div class="banner" _="install Removable(removeButton: #close-banner)">
...

This works well, but now our original div is broken. We can use an init block to set a default value for the parameter:

behavior Removable(removeButton)
  init
    if no removeButton set the removeButton to me
  end

  on click from removeButton
    remove me
  end
end

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