scopeBind

[ ru ]

Formulae

scopeBind<T>(event: Event<T>): (payload: T) => void
scopeBind<T>(event: Event<T>, options?: {scope?: Scope, safe?: boolean }): (payload: T) => void

A method to bind event or effect to a Scope to be called later. effector supports imperative event calling inside watchers, but sometimes you should bind events to the scope explicitly, e.g. when calling events within a setTimeout/setInterval callbacks.

Arguments

  1. event EventCallable or Effect to be bound to the scope
  2. options (Object): Optional configuration
    • scope (Scope): scope binding event to
    • safe (Boolean): flag for exception supression if there is no scope.

Example

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

See full example

Arbitrary сallback in scopeBind

Binds arbitary callback to a scope to be called later. The “Bounded” version of the function preserves all properties of the original - e.g. if original would throw if called with some specific argument, then bounded version will also throw, when called with this argument.

since

Feature is available since effector 23.1.0 release.

warning

Notice, that to be compatible with Fork API, callbacks must follow the same rules as Effect handlers:

export function scopeBind<T extends Function>(
  fn: T,
  options?: { scope?: Scope; safe?: boolean },
): T;

Arguments

  1. fn any function to be bound to the scope
  2. options (Object): Optional configuration
    • scope (Scope): scope binding event to
    • safe (Boolean): flag for exception supression if there is no scope.

Example {$scopeBind-arbitary-example}

const locationChanged = createEvent();

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