Pauan / rust-dominator

Zero-cost ultra-high-performance declarative DOM library using FRP signals for Rust!
MIT License
960 stars 62 forks source link

Add block support to `apply_methods!` macro #64

Closed tqwewe closed 2 years ago

tqwewe commented 2 years ago

Adds support for more dynamic methods in the apply_methods! macro.

This is done with the syntax of a closure.

html!("div", {
    |this| {
        this.event(...)
    };
});

This is needed for more advanced cases such as cases where you need to return data temporarily to a method. For example, this doesn't work:

html!("div", {
    .text(match format_args("foo").as_str() {
        Some(s) => s,
        None => &format!("foo"), // Fails, because this does not live past the match block.
    })
});

With this PR, you can now do this instead:

html!("div", {
    |this| match format_args("foo").as_str() {
        Some(s) => this.text(s),
        None => this.text(&format!("foo")),
    };
});
Pauan commented 2 years ago

What's the advantage of this over using apply?

html!("div", {
    .apply(|this| {
        this.event(...)
    })
})
html!("div", {
    .apply(|this| match format_args("foo").as_str() {
        Some(s) => this.text(s),
        None => this.text(&format!("foo")),
    })
})
tqwewe commented 2 years ago

I actually wasn't really aware of apply. I think apply is actually exactly what I needed