DEV Community

Jay Landrum
Jay Landrum

Posted on

Handling Events

Many JavaScript libraries seem intent on wrapping browser events in some custom event object. Libraries like jQuery and Angular hide the original Event object behind a custom type that may be useful to the library but I can't remember it ever being useful to me.

My goal for handling events was to keep it simple. Registering an event on an element in the framework is effectively the same as calling .AddEventListener(...). The only responsibility of the framework is to manage or clean up those events.

Registering an Event

Events are registered using the on property of the element configuration object. This property takes an object with event names as properties.

div({ 
  on: { 
      click: (event: Event) => alert('Hello World') 
  }, 
  () => "Click!"
)
Enter fullscreen mode Exit fullscreen mode

Component events

Components define supported events through the third generic parameter of the Component<void, void, E> class. The second type parameter is for defining templates and covered in a future post. The component events type is expected to be a map of event names associated with the type of data emitted by the event. A component can fire an event by calling this.Fire(eventName: string).

Listening for a component event also uses the on property of the component configuration object. Component event callbacks take a single parameter typed by the event map. Components do not fire standard DOM events.

type Events = {
  alert: string;
};

class ChildComponent extends Component<void, void, Events> {
  Template() {
    return div(
      {
        on: { click: () => this.Fire("alert", "Hello from ChildComponent") }
      },
      () => "Child click!"
    );
  }
}

const childComponent = Component.ToFunction(
  "child-component",
  null,
  ChildComponent
);

class HelloWorld extends Component<void, void, Events> {
  Template() {
    return
      childComponent({ on: { alert: (message) => alert(message) } });
  }
}
Enter fullscreen mode Exit fullscreen mode

Code Sandbox

Next post will cover adding reactivity to components.

Top comments (0)