as
Expression <expression> as [ a | an ] CONVERSION
Hyperscript provides a pluggable conversion system with the as
expression. It will look up the conversion of the given name and apply it to the input expression.
By default, hyperscript provides the following conversions:
Array
- convert to ArrayDate
- convert to DateFloat
- convert to floatFragment
- converts a string into an HTML FragmentHTML
- converts NodeLists and arrays to an HTML stringInt
- convert to integerJSON
- convert to a JSON StringNumber
- convert to numberObject
- convert from a JSON StringString
- convert to StringValues
- converts a Form (or other element) into a struct containing its input names/valuesValues:Form
- converts a Form (or other element) into form encoded stringValues:JSON
- converts a Form (or other element) into json encoded stringFixed<:N>
- convert to a fixed precision string representation of the number, with an optional precision of N
Some examples:
log '10' as Int -- logs 10
log '3.141568' as Fixed:2 -- logs '3.14'
log '{"foo":10}' as Object -- logs { "foo": 10 }'
log 10 as String -- logs "10"
You can add new conversions by adding them to the _hyperscript.config.conversions
object:
_hyperscript.config.conversions["MyConversion"] = function (val) {
return "I converted: " + val;
};
which can then be used like so in hyperscript:
<button _="on click put 'foo' as MyConversion into my innerHTML">
Call my conversion
</button>
You also have the option to create a dynamic conversion, which will be called before all conversions, and allow you to create more flexible conversion naming schemes
_hyperscript.config.conversions.dynamicResolvers.push(function (
conversionName,
val
) {
if (conversionName.indexOf("MyConversion:") == 0) {
var arg = conversionName.split(":")[1];
if (arg === "Short") {
return "I converted : " + val;
} else if (arg === "Long") {
return "I am happy to announce I converted : " + val;
}
}
});
This conversion could now be used like so:
<button _="on click put 'foo' as MyConversion:Short into my innerHTML">
Call my conversion
</button>