Function leptos_reactive::create_selector
source · pub fn create_selector<T>(
cx: Scope,
source: impl Fn() -> T + Clone + 'static
) -> impl Fn(T) -> bool + Clonewhere
T: PartialEq + Eq + Debug + Clone + Hash + 'static,
Expand description
Creates a conditional signal that only notifies subscribers when a change in the source signal’s value changes whether it is equal to the key value (as determined by PartialEq.)
You probably don’t need this, but it can be a very useful optimization
in certain situations (e.g., “set the class selected
if selected() == this_row_index
)
because it reduces them from O(n)
to O(1)
.
let (a, set_a) = create_signal(cx, 0);
let is_selected = create_selector(cx, a);
let total_notifications = Rc::new(RefCell::new(0));
let not = Rc::clone(&total_notifications);
create_isomorphic_effect(cx, {
let is_selected = is_selected.clone();
move |_| {
if is_selected(5) {
*not.borrow_mut() += 1;
}
}
});
assert_eq!(is_selected(5), false);
assert_eq!(*total_notifications.borrow(), 0);
set_a(5);
assert_eq!(is_selected(5), true);
assert_eq!(*total_notifications.borrow(), 1);
set_a(5);
assert_eq!(is_selected(5), true);
assert_eq!(*total_notifications.borrow(), 1);
set_a(4);
assert_eq!(is_selected(5), false);