import {Meta} from '@storybook/addon-docs/blocks'

<Meta title='@dxtmisha/en/functional-basic/# Event management'/>

# Event management

The `EventItem` class is an advanced wrapper for managing event listeners on DOM elements or the `window` object. It simplifies the entire event lifecycle, provides automatic monitoring of element existence in the DOM, and includes built-in optimizations for high-frequency events.

```javascript
import { EventItem } from '@dxtmisha/functional-basic'

// 1. Initialization
const event = new EventItem('.my-button', 'click', () => {
  console.log('Button clicked!')
})

// 2. Lifecycle management
event.start()  // Start listening
event.stop()   // Stop listening
event.toggle(true) // Toggle state
```

## Element Monitoring

One of the key features of `EventItem` is the automatic deactivation of an event if the target element (or control element) is removed from the DOM. This prevents memory leaks and errors in dynamic interfaces.

```javascript
// The event will automatically stop if the .my-button element disappears from the DOM
const event = new EventItem('.my-button', 'scroll', handler)
event.start()
```

## Performance Optimization

The class includes built-in optimization mechanisms for heavy events such as window resizing or scroll synchronization.

### Type `resize`
Uses `ResizeObserver` instead of the standard `resize` event, allowing you to track the size change of a specific element, not just the entire window.

```javascript
const resizeEvent = new EventItem('.container', 'resize', (entry) => {
  console.log('New width:', entry.contentRect.width)
})
```

### Type `scroll-sync`
Optimizes scroll handling via `requestAnimationFrame`, preventing redundant handler calls and reducing CPU load.

```javascript
const scrollEvent = new EventItem(window, 'scroll-sync', () => {
  // Executes as smoothly as possible
})
```

## Manual Event Dispatch

You can manually trigger the event on the target element using the `dispatch` method. This is useful for programmatically simulating user actions.

```javascript
// Simulate a click
event.dispatch()

// Passing additional data (detail)
const customEvent = new EventItem(window, 'my-event', (e, detail) => {
  console.log('Data:', detail)
})
customEvent.dispatch({ id: 123 })
```
