Documentation
About Installation Guide Data Views Components Examples

Views

Moon views are defined using the Moon View Language. The Moon view language is a template language based on HTML and adds support for data interpolation, events, and components.

Interpolation

Properties from instance data can be interpolated into the view using a pair of curly braces: {}.

<div class={name}>
    {message}
</div>
Moon({
    root: "#root",
    name: "interpolation",
    message: "Hello Moon!"
});

Try entering ViewInterpolation.update("message", "New Message!") in the console to update the view.

Events

Browser events, component events, and lifecycle events can be handled by using an attribute starting with @.

Browser Events

Browser events such as click or input can be handled by creating an attribute prepended with @ with one statement as a value. A special local variable named $event will be available and holds the event object.

<button @click={announce($event)}>
    Make Announcement
</button>
Moon({
    root: "#root",
    announce($event) {
        alert($event.target.tagName + " was clicked.");
    }
});
Bind Events

The bind event is a special event used to bind an input value to a variable and a variable to the input value.

<p>{text}</p>
<input type="text" @bind={text}/>
Moon({
    root: "#root",
    text: "Hello Moon!"
});

Try entering ViewBindEvents.update("text", "New Text!") in the console to update the view.

Component Events

Learn about component events in the components section.

Conditionals

Elements can be rendered based on certain conditions using the If, ElseIf, and Else components.

<div If={condition}>
    Condition is truthy.
</div>
<div Else>
    Condition is falsy.
</div>
Moon({
    root: "#root",
    condition: Math.random() <= 0.5 ? false : true
});

Try entering ViewConditionals.update("condition", !ViewConditionals.condition) in the console to update the view.

Loops

Elements can be rendered multiple times for every element in an array using the For component. The syntax for the main argument is $element,$index in array. The element and index are prefixed with $, meaning that they are locals and not on the instance itself.

<ul>
    <li For={$item,$index in items}>
        {$index}: {$item}
    </li>
</ul>
Moon({
    root: "#root",
    items: ["foo", "bar", "baz"]
});

Try entering ViewLoops.update("items", ViewLoops.items.reverse()) in the console to update the view.

Alternate Syntax

Since If, ElseIf, Else, and For are just components, you can use the normal component syntax.

<If={condition}>
    <p>Condition is truthy.</p>
    <p>Multiple elements are allowed.</p>
</If>
<Else>
    <p>Condition is falsy.</p>
</Else>

<For={$item,$index in items}>
    <p>{$item}</p>
    <p>{$index}</p>
</For>