Skip to content

Events

js-toolkit automatically binds class methods that start with on as event handlers. The method name determines what event is listened to and on which target:

  • the component itself with on<CustomEventName>
  • the root element of the component with on<NativeEventName>
  • the global window object with onWindow<NativeEventName>
  • the global document object with onDocument<NativeEventName>
  • any refs defined with on<RefName><NativeEventName>
  • any child component with on<ChildName><CustomEventName>

The following methods can be used:

js
import { Base } from '@studiometa/js-toolkit';
import Child from './Child.js';

class App extends Base {
  static config = {
    name: 'App',
    emits: ['custom-event'],
    refs: ['btn'],
    components: {
      Child,
    },
  };

  // Runs when the user clicks `this.$el`
  onClick({ event, index, target, args }) {}

  // Runs when the instance emits the `custom-event`
  onCustomEvent({ event, index, target, args }) {}

  // Runs when the user clicks the `window`
  onWindowClick({ event, index, target, args }) {}

  // Runs when the user clicks the `document`
  onDocumentClick({ event, index, target, args }) {}

  // Runs when the user clicks the `btn` ref
  onBtnClick({ event, index, target, args }) {}

  // Runs when the user clicks any `Child` component
  onChildClick({ event, index, target, args }) {}
}

All methods receive a single context parameter:

Event callback parameter type
ts
type EventHooksCallbackParams = {
  /**
   * The event emitted
   */
  event: Event;
  /**
   * If the event is emitted on a component, given arguments
   * can be accessed with the `args` property.
   */
  args: Array<any>;
  /**
   * If the event is emitted on multiple refs or children, the `index`
   * property will be the index of the current target.
   */
  index: number;
  /**
   * The target that emitted the event.
   */
  target: Element | Base | Promise<Base> | typeof window | typeof document;
};

See also: Event hooks · Instance events

MIT Licensed