Pauan / rust-dominator

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

How to use child_signal #56

Closed tokcum closed 2 years ago

tokcum commented 2 years ago

Hi,

I'm trying to use child_signal() but struggle to create a Signal<Item = Option> as required by the trait bound. I assume, I've to use signal_ref() as Dom does neither implement Copy nor Clone, so signal() and signal_cloned do not work. Correct?

This is what I have put together so far. I guess, I'm missing something obvious or misunderstand the approach completely. A example code showing how this is meant to be used would be great.

let dom = Mutable::new(Some(Dom::empty()));
let signal = dom.signal_ref(|d| d );

let header: DomBuilder<web_sys::HtmlElement> = DomBuilder::new_html("header");
header.child_signal(signal);

This is the compiler error:

error[E0271]: type mismatch resolving `for<'r> <[closure@webapp/src/lib.rs:35:33: 35:38] as FnOnce<(&'r Option<Dom>,)>>::Output == Option<Dom>`
  --> webapp/src/lib.rs:38:12
   |
38 |     header.child_signal(signal);
   |            ^^^^^^^^^^^^ expected `&Option<Dom>`, found enum `Option`
   |
   = note: expected reference `&Option<Dom>`
                   found enum `Option<Dom>`
   = note: required because of the requirements on the impl of `Signal` for `MutableSignalRef<Option<Dom>, [closure@webapp/src/lib.rs:35:33: 35:38]>`

Any help appreciated. Thanks.

Pauan commented 2 years ago

In general you shouldn't be storing Dom inside of a Mutable. That's because child_signal and children_signal_vec require owned values, and signal_ref gives you a reference, not an owned value.

It's also not good design, because you're conflating your app's data with your app's rendering. Instead you should be storing your app's data inside of the Mutable, and use map to convert it into a Dom.

It would really help if you could explain what you're trying to do. Your code doesn't really tell me very much.

tokcum commented 2 years ago

Thanks Pauan, I just wanted to know how to use signal_ref. Thanks to your guidance, I understood the approach. I never really wanted to have a Mutable. I just struggled with the closure in signal_ref. Now I understand that the closure has to return an Option. So I pass a closure to signal_ref which creates a Dom from the data in the Mutable.

Tata: it works! Thanks again. 🙂