Back to Nocobase

ctx.off()

docs/docs/en/runjs/context/off.md

2.0.611.3 KB
Original Source

ctx.off()

Removes a listener registered with ctx.on(eventName, handler). Use with ctx.on and unsubscribe when appropriate to avoid leaks or duplicate triggers.

Use Cases

ScenarioDescription
React useEffect cleanupCall in useEffect cleanup; remove on unmount
JSField / JSEditableFieldUnsubscribe from js-field:value-change when doing two-way binding
resourceUnsubscribe from ctx.resource.on (refresh, saved, etc.)

Type

ts
off(eventName: string, handler: (event?: any) => void): void;

Examples

Pair with on in useEffect

tsx
React.useEffect(() => {
  const handler = (ev) => setValue(ev?.detail ?? '');
  ctx.on('js-field:value-change', handler);
  return () => ctx.off('js-field:value-change', handler);
}, []);

Unsubscribe resource event

ts
const handler = () => { /* ... */ };
ctx.resource?.on('refresh', handler);
// Later
ctx.resource?.off('refresh', handler);

Notes

  1. Same handler reference: The handler passed to ctx.off must be the same reference as in ctx.on, or it will not be removed.
  2. Clean up in time: Call ctx.off before unmount or context destroy to avoid leaks.