Add Callback::from_fn_mut

Cursive::add_global_callback now takes a FnMut
This commit is contained in:
Alexandre Bury 2018-07-25 15:00:29 -07:00
parent b2d800c798
commit 28bb7af6af
2 changed files with 19 additions and 2 deletions

View File

@ -514,12 +514,12 @@ impl Cursive {
/// ```
pub fn add_global_callback<F, E: Into<Event>>(&mut self, event: E, cb: F)
where
F: Fn(&mut Cursive) + 'static,
F: FnMut(&mut Cursive) + 'static,
{
self.global_callbacks
.entry(event.into())
.or_insert_with(Vec::new)
.push(Callback::from_fn(cb));
.push(Callback::from_fn_mut(cb));
}
/// Removes any callback tied to the given event.

View File

@ -14,6 +14,7 @@
//! table is checked.
use std::any::Any;
use std::cell::RefCell;
use std::ops::Deref;
use std::rc::Rc;
use vec::Vec2;
@ -39,6 +40,22 @@ impl Callback {
})))
}
/// Wrap a `FnMut` into a `Callback` object.
///
/// If this methods tries to call itself, nested calls will be no-ops.
pub fn from_fn_mut<F>(f: F) -> Self
where
F: 'static + FnMut(&mut Cursive),
{
let cb = RefCell::new(f);
Self::from_fn(move |s| {
if let Ok(mut cb) = cb.try_borrow_mut() {
(&mut *cb)(s);
}
})
}
/// Returns a dummy callback that doesn't run anything.
pub fn dummy() -> Self {
Callback::from_fn(|_| ())