import { scopeBind } from "effector";
scopeBind
is a method to bind a unit (an Event or Effect) to a Scope to be called later. Effector supports imperative calling of events within watchers, however, there are instances where you must explicitly bind events to the scope, such as when triggering events from within setTimeout
or setInterval
callbacks.
Methods
scopeBind(event, options?)
Formulae
scopeBind<T>(event: EventCallable<T>): (payload: T) => void
scopeBind<T>(event: EventCallable<T>, options?: {scope?: Scope, safe?: boolean}): (payload: T) => void
Arguments
event
EventCallable or Effect to be bound to the scope.options
(Object): Optional configuration.scope
(Scope): Scope to bind event to.safe
(Boolean): Flag for exception suppression if there is no scope.
Returns
(payload: T) => void
— A function with the same types as event
.
Examples
Basic Usage
We are going to call changeLocation
inside history.listen
callback so there is no way for effector to associate event with corresponding scope, and we should explicitly bind event to scope using scopeBind
.
const $history = createStore(history);
const initHistory = createEvent();
const changeLocation = createEvent<string>();
const installHistoryFx = attach({
source: $history,
effect: (history) => {
const locationUpdate = scopeBind(changeLocation);
history.listen((location) => {
locationUpdate(location);
});
},
});
sample({
clock: initHistory,
target: installHistoryFx,
});
scopeBind(callback, options?)
Binds arbitrary callback to a scope to be called later. The bound version of the function retains all properties of the original, e.g., if the original function would throw when called with a certain argument, the bound version will also throw under the same circumstances.
Feature is available since effector 23.1.0
release.
To be compatible with the Fork API, callbacks must adhere to the same rules as Effect
handlers:
- Synchronous functions can be used as they are.
- Asynchronous functions must follow the rules described in “Imperative Effect calls with scope”.
Formulae
scopeBind(callback: T, options?: { scope?: Scope; safe?: boolean }): (payload: T) => void;
Arguments
callback
(Function): Any function to be bound to the scope.options
(Object): Optional configuration.scope
(Scope): Scope to bind the event to.safe
(Boolean): Flag for exception suppression if there is no scope.
Returns
(payload: T) => void
— A function with the same types as callback
.
Examples
const locationChanged = createEvent();
const listenToHistoryFx = attach({
source: $history,
effect: (history) => {
return history.listen(
scopeBind((location) => {
locationChanged(location);
}),
);
},
});