Skip to content

@jtjs/event

API | Package

Environment: Any

@jtjs/event provides a simple but powerful object-oriented event implementation. It has no dependencies, is extremely lightweight, and is fully typed.

  1. Create your event:

    import { Event } from '@jtjs/event';
    type ThemeChangeHandler = (themeName: string) => void;
    const onThemeChange = new Event<ThemeChangeHandler>();
  2. Subscribe to your event…

    • Until you unsubscribe:

      onThemeChange.subscribe((themeName) => {
      console.log(`Theme changed to ${themeName}!`);
      });
    • For just one trigger:

      onThemeChange.once((themeName) => {
      console.log('Just once!');
      });
  3. Trigger your event:

    onThemeChange.trigger('light');
  4. Unsubscribe from your event…

    • With the return from subscribe:

      const unsub = onThemeChange.subscribe((themeName) => {
      console.log('beep boop');
      });
      unsub();
    • With the reference to your handler:

      const handler = (themeName: string) => {
      console.log('beep boop');
      };
      onThemeChange.subscribe(handler);
      onThemeChange.unsubscribe(handler);