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

  1. event EventCallable or Effect to be bound to the scope.
  2. 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.

import {createStore, createEvent, attach, scopeBind} from 'effector';

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,
});

See full example

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.

since

Feature is available since effector 23.1.0 release.

warning

To be compatible with the Fork API, callbacks must adhere to the same rules as Effect handlers:

Formulae

scopeBind(callback: T, options?: { scope?: Scope; safe?: boolean }): (payload: T) => void;

Arguments

  1. callback (Function): Any function to be bound to the scope.
  2. 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

import {createEvent, createStore, attach, scopeBind} from 'effector'

const $history = createStore(history);
const locationChanged = createEvent();

const listenToHistoryFx = attach({
  source: $history,
  effect: (history) => {
    return history.listen(
      scopeBind((location) => {
        locationChanged(location);
      }),
    );
  },
});
Contributors