Skip to content

Event Listeners

Listner provides a powerful event-driven architecture that allows you to react to various list operations by registering event listeners. This feature is particularly useful for tracking changes to your lists in real-time, such as when items are added, updated, or removed.

Setting Up Listeners

to set up listeners with Listner, you first need to create an instance of the ListManager class, specifying the type of items your list will hold. Then, you can use the .on() method to register event listeners for different list operations.

Below is an example of how to set up a listener for the insert event, which is triggered whenever a new item is added to the list.

ts
import { ListManager } from 'listner';

interface Person {
  id: number;
  name: string;
  age?: number;
  verified?: boolean;
  sex?: "male" | "female";
}

// Create a new ListManager instance
const list = new ListManager<Person>();

// Register an event listener for the 'insert' event
list.on("insert", (data) => {
  console.log(`New item inserted: ${data.name}`);
})

To remove an event listener, you can use the off method provided by Listner. This method allows you to unregister an event listener, stopping it from receiving further event notifications. Here's how you can use off in conjunction with the previously registered event listeners:

ts
list.off("insert");

Supported Events

Listner supports a variety of events that you can listen to. Each event provides relevant data as arguments to the event handler function, allowing you to perform custom logic based on the event. Here are some of the events supported by Listner:

  • insert: Triggered when a new item is added to the list.
  • update: Triggered when an item in the list is updated.
  • delete: Triggered when an item is removed from the list.
  • clear: Triggered when the list is cleared