usecallback.rs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. use std::{cell::RefCell, rc::Rc};
  2. use crate::use_state;
  3. use crate::UseFutureDep;
  4. use dioxus_core::{ScopeState, UiEvent};
  5. use std::future::Future;
  6. pub fn use_callback<I, G: UseFutureDep, F: Future<Output = ()> + 'static>(
  7. cx: &ScopeState,
  8. //
  9. g: G,
  10. f: impl FnMut(I, G::Out) -> F,
  11. ) -> &UseCallback<I, G::Out>
  12. where
  13. G::Out: 'static,
  14. I: 'static,
  15. {
  16. cx.use_hook(|_| {
  17. //
  18. UseCallback {
  19. f: todo!(),
  20. f2: Box::new(|f| {}),
  21. }
  22. })
  23. }
  24. pub struct UseCallback<I, T> {
  25. f: Rc<RefCell<Option<Box<dyn FnMut(I, T)>>>>,
  26. f2: Box<dyn Fn(I)>, // f: Rc<RefCell<Option<Box<dyn FnMut(I, T)>>>>,
  27. }
  28. impl<I: 'static, T> std::ops::Deref for UseCallback<I, T> {
  29. type Target = dyn Fn(I);
  30. fn deref(&self) -> &Self::Target {
  31. &self.f2
  32. }
  33. }
  34. trait MyThing {}
  35. impl<A> MyThing for Box<dyn Fn(A)> {}
  36. impl<A, B> MyThing for Box<dyn Fn(A, B)> {}
  37. #[test]
  38. fn demo() {
  39. use dioxus_core::prelude::*;
  40. fn example(cx: Scope) -> Element {
  41. let (name, _) = use_state(&cx, || 0);
  42. let (age, _) = use_state(&cx, || 0);
  43. let onsubmit = use_callback(&cx, (name,), |event: (), (name,)| async move {
  44. //
  45. });
  46. let onsubmit = use_callback(&cx, (name,), my_callback);
  47. async fn my_callback(event: UiEvent<()>, name: (i32,)) {
  48. //
  49. }
  50. let onsubmit = use_callback(&cx, name, my_callback2);
  51. async fn my_callback2(event: UiEvent<()>, name: i32) {
  52. //
  53. }
  54. None
  55. }
  56. }