NAME

Chandra::Component - Reactive UI components for Chandra

SYNOPSIS

package MyCounter;
use Object::Proto;

BEGIN {
    object 'MyCounter',
        extends => 'Chandra::Component',
        'count:Int:default(0)',
        'label:Str:default(Counter)',
    ;
    Object::Proto::import_accessors('MyCounter');
}

sub render {
    my ($self) = @_;
    my $count = $self->count;
    my $label = $self->label;
    return qq{
        <div class="counter">
            <h2>$label: $count</h2>
            <button data-action="increment">+</button>
            <button data-action="decrement">-</button>
        </div>
    };
}

sub on_increment { $_[0]->count($_[0]->count + 1); $_[0]->update }
sub on_decrement { $_[0]->count($_[0]->count - 1); $_[0]->update }

# Usage:
my $counter = MyCounter->new(label => 'Clicks');
$counter->mount($app, '#main');

DESCRIPTION

Chandra::Component is an Object::Proto-based reactive component system. Components encapsulate state, rendering, and event handling.

Lifecycle

mount($app, $selector) - render + inject into DOM, bind events
unmount() - remove from DOM, unbind events
update() - re-render the component's DOM subtree

Lifecycle Hooks (override in subclass)

on_mount() - called after first render
on_unmount() - called before removal
on_update() - called after re-render

Event Binding

Use data-action="method_name" in your HTML. Clicking the element calls on_method_name() on the component. Parameters can be passed with data-action="method:arg1:arg2".

Children

$parent->child($child_component);

Children are rendered inside the parent and automatically mounted/unmounted with it.

METHODS

new(%slots)

Makes a component. Object::Proto builds the object from the slots the subclass declared, then BUILD runs.

BUILD

Gives the component its id and puts it in the registry. A subclass with its own BUILD calls this one.

child($component)

Adds a child component, which renders inside this one and mounts with it. Returns the parent.

render_children

The children's html, each wrapped with its id.

update_part($id, $html)

Replaces one element inside a mounted component, after rewriting the data-action attributes in the html. Returns the component.

find_component($id)

Class method. The live component with that id, or undef.

reset

Class method. Empties the registry and starts the ids again.

prototype, set_prototype

Object::Proto's prototype accessors, inherited by every component.

SLOT ACCESSORS

Object::Proto makes a function for each slot, imported with the comp_ prefix, and a method of the slot's name.

comp__cid - the component id
comp__app - the app the component is mounted on
comp__selector - the selector it was mounted into
comp__mounted - whether it is mounted
comp__children - the child components
comp__parent - the parent component, held weakly

SEE ALSO

Chandra::App, Chandra::Element