Comments (1)
since I needed this I've hacked something together (mostly copy-paste of dioxus code, plus one argument) that appears to work for me. Let me know if this looks plausible and if so I'll create a PR!
pub fn use_callback1<T, O>(f: impl FnMut(T) -> O + 'static) -> UseCallback1<O, T> {
// Create a copyvalue with no contents
// This copyvalue is generic over F so that it can be sized properly
let mut inner = use_hook(|| CopyValue::new(None));
// Every time this hook is called replace the inner callback with the new callback
inner.set(Some(f));
// And then wrap that callback in a boxed callback so we're blind to the size of the actual callback
use_hook(|| {
let cur_scope = current_scope_id().unwrap();
let rt = Runtime::current().unwrap();
UseCallback1 {
inner: CopyValue::new(Box::new(move |arg1| {
// run this callback in the context of the scope it was created in.
let run_callback = || inner.with_mut(|f: &mut Option<_>| f.as_mut().unwrap()(arg1));
rt.on_scope(cur_scope, run_callback)
})),
}
})
}
/// This callback is not generic over a return type so you can hold a bunch of callbacks at once
///
/// If you need a callback that returns a value, you can simply wrap the closure you pass in that sets a value in its scope
#[derive(PartialEq)]
pub struct UseCallback1<O: 'static + ?Sized, T: 'static> {
inner: CopyValue<Box<dyn FnMut(T) -> O>>,
}
impl<O: 'static + ?Sized, T> Clone for UseCallback1<O, T> {
fn clone(&self) -> Self {
Self { inner: self.inner }
}
}
impl<O: 'static, T: 'static> Copy for UseCallback1<O, T> {}
impl<O, T> UseCallback1<O, T> {
/// Call the callback
pub fn call(&self, arg1: T) -> O {
(self.inner.write_unchecked())(arg1)
}
}
// This makes UseCallback callable like a normal function
impl<O, T> std::ops::Deref for UseCallback1<O, T> {
type Target = dyn Fn(T) -> O;
fn deref(&self) -> &Self::Target {
// https://github.com/dtolnay/case-studies/tree/master/callable-types
// First we create a closure that captures something with the Same in memory layout as Self (MaybeUninit<Self>).
let uninit_callable = MaybeUninit::<Self>::uninit();
// Then move that value into the closure. We assume that the closure now has a in memory layout of Self.
let uninit_closure = move |arg1| Self::call(unsafe { &*uninit_callable.as_ptr() }, arg1);
// Check that the size of the closure is the same as the size of Self in case the compiler changed the layout of the closure.
let size_of_closure = std::mem::size_of_val(&uninit_closure);
assert_eq!(size_of_closure, std::mem::size_of::<Self>());
// Then cast the lifetime of the closure to the lifetime of &self.
fn cast_lifetime<'a, T>(_a: &T, b: &'a T) -> &'a T {
b
}
let reference_to_closure = cast_lifetime(
{
// The real closure that we will never use.
&uninit_closure
},
// We transmute self into a reference to the closure. This is safe because we know that the closure has the same memory layout as Self so &Closure == &Self.
unsafe { std::mem::transmute(self) },
);
// Cast the closure to a trait object.
reference_to_closure as &_
}
}
from dioxus.
Related Issues (20)
- Assigning a port number when using `dx serve --port [number]` on fullstack is not respected. HOT 2
- Ctrl/cmd click does not open in a new tab/window
- Dioxus-cli ignores env variables in `.cargo/config.toml` HOT 2
- pointermove events on Windows crash with InvalidType HOT 3
- [Desktop] Hot reloading does not work in the "tailwind" sample
- question: custom rendering to arbitrary wayland surface HOT 3
- Hydration error when using use_server_future in certain contexts in Fullstack
- Docs have a couple outdated examples
- how to spawn a thread in main or other place only once HOT 2
- Add `-p package` option to Dioxus CLI HOT 1
- Rerender fails when rendering an iterable with `None` elements inside
- how to send channel to child component HOT 8
- `use_reactive` inside `use_memo` causes infinite re-renders HOT 2
- `rsx` macro should prevent any children in self-closing elements
- Provide type checking support for HTML attribute values in `rsx` macro
- HTML String into rsx! HOT 1
- Update TailwindCSS Example Project HOT 2
- Add support for attaching event listeners to the global window HOT 2
- Hot reload doesn't turn off when using `--hot-reload=false`
- Assets in Dioxus build are "unpacked" from the original directory
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from dioxus.