maciejhirsz / kobold

Easy declarative web interfaces.
https://docs.rs/kobold/
Mozilla Public License 2.0
385 stars 7 forks source link

Update `bind!` documentation to show example of equivalent techniques using `state` #54

Closed ltfschoen closed 1 year ago

ltfschoen commented 1 year ago

In the docs here, it shows how to use bind!

In the invoice example, I wanted an editable input field, and I wanted to be able to load from a file (like your csv example), and populate the editable fields value with a value from the file, and still have that input field being editable (like your csv example).

But I there were different techniques being used in the examples. After I got it to work I found that the following:

#[component]
fn MyView<'a>(state: &'a Hook<State>) -> impl View + 'a {
    let ondblclick = state.bind(move |s, _| s.entry.editing = true);
    view! {
        <div {ondblclick} >click to edit</div>
    }
}

is equivalent to this:

#[component]
fn MyView<'a>(state: &'a Hook<State>) -> impl View + 'a {
    bind! { state:
        let ondblclick = move |_| state.editing = true;
    }
    view! {
        <div {ondblclick} >click to edit</div>
    }
}

So in the examples the following:

bind! { state:
    let onchange = move |e: Event<InputElement>| {
        state.table.rows[0][0] = Text::Owned(e.target().value().into());
        state.editing = false;
    };
}

is equivalent to this:

let onchange = state.bind(move |state, e: Event<InputElement>| {
    state.table.rows[0][0] = Text::Owned(e.target().value().into());
    state.editing = false;
});

If I have another look at the docs it does show how it's desugered, but it wasn't immediately obvious to me. Could it be beneficial to update the bind docs to show an example with both options using the state?

ltfschoen commented 1 year ago

After a bit more reading i found this method bind, which is the one I used to be able to do state.bind. It does say "While this method is public it’s recommended to use the bind! macro instead.".

Why is the bind! macro recommended over using this bind method?

maciejhirsz commented 1 year ago

Why is the bind! macro recommended over using this bind method?

Because I estimate that the macro is more ergonomic and at this point more stable (less likely to have breaking changes in the future) than the method. For that reason I also prefer to keep the documentation focused on the bind! macro.

Down the line I'd like to make that macro unnecessary by basically auto-binding event handlers in components, pushing Kobold more towards a proper DSL (which it already kind of is).