1
0

usecallback.rs 1.4 KB

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