npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@avatijs/listener

v0.1.1

Published

Listener package part of Avati project

Downloads

61

Readme

EventListenerManager HTML Showcases

Below are practical HTML examples demonstrating how to use the EventListenerManager in a web page. Each example illustrates different features and use cases, such as debouncing, throttling, asynchronous callbacks, error handling, and metadata attachment.


Prerequisites

To use the EventListenerManager in your HTML files, you need to include it in your project. Assuming you have the compiled JavaScript version of the EventListenerManager, you can include it using a <script> tag.

For demonstration purposes, we'll assume the EventListenerManager is available in a file named EventListenerManager.js.


1. Basic Usage

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>EventListenerManager - Basic Usage</title>
</head>
<body>
  <button id="myButton">Click Me</button>

  <!-- Include the EventListenerManager script -->
  <script src="EventListenerManager.js"></script>
  <script>
    // Wait for the DOM to load
    document.addEventListener('DOMContentLoaded', () => {
      const button = document.getElementById('myButton');

      function handleClick(event) {
        alert('Button clicked!');
      }

      // Add an event listener using EventListenerManager
      const eventId = eventManager.add(button, 'click', handleClick);

      // Optionally, remove the event listener after some time
      setTimeout(() => {
        eventManager.remove(eventId);
        console.log('Event listener removed');
      }, 10000); // Removes the listener after 10 seconds
    });
  </script>
</body>
</html>

Explanation

  • We include the EventListenerManager.js script in the HTML file.
  • We use eventManager.add() to attach a click event listener to the button.
  • After 10 seconds, we remove the event listener using eventManager.remove().

2. Debouncing Input Events

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>EventListenerManager - Debounce Example</title>
  <style>
    #output {
      margin-top: 20px;
    }
  </style>
</head>
<body>
  <input type="text" id="searchInput" placeholder="Type to search..." />
  <div id="output"></div>

  <!-- Include the EventListenerManager script -->
  <script src="EventListenerManager.js"></script>
  <script>
    document.addEventListener('DOMContentLoaded', () => {
      const input = document.getElementById('searchInput');
      const output = document.getElementById('output');

      function handleInput(event) {
        const query = event.target.value;
        output.textContent = `Searching for: ${query}`;
      }

      // Debounce the input event handler
      eventManager.add(input, 'input', handleInput, { debounce: 500 });
    });
  </script>
</body>
</html>

Explanation

  • As the user types in the input field, the handleInput function is called after the user stops typing for 500 milliseconds.
  • This reduces the number of times the search function is called, which is especially useful when making API requests.

3. Throttling Scroll Events

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>EventListenerManager - Throttle Example</title>
  <style>
    body {
      height: 2000px;
    }
    #scrollPosition {
      position: fixed;
      top: 10px;
      left: 10px;
      background: rgba(255, 255, 255, 0.8);
      padding: 5px;
    }
  </style>
</head>
<body>
  <div id="scrollPosition">Scroll Y: 0</div>

  <!-- Include the EventListenerManager script -->
  <script src="EventListenerManager.js"></script>
  <script>
    document.addEventListener('DOMContentLoaded', () => {
      const scrollDisplay = document.getElementById('scrollPosition');

      function handleScroll() {
        scrollDisplay.textContent = `Scroll Y: ${window.scrollY}`;
      }

      // Throttle the scroll event handler
      eventManager.add(window, 'scroll', handleScroll, { throttle: 100 });
    });
  </script>
</body>
</html>

Explanation

  • The handleScroll function updates the displayed scroll position.
  • By throttling the scroll event handler to 100 milliseconds, we limit the number of times the function is called during scrolling, improving performance.

4. Using Async Callbacks

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>EventListenerManager - Async Callback Example</title>
</head>
<body>
  <form id="myForm">
    <input type="text" name="data" placeholder="Enter some data" required />
    <button type="submit">Submit</button>
  </form>
  <div id="status"></div>

  <!-- Include the EventListenerManager script -->
  <script src="EventListenerManager.js"></script>
  <script>
    document.addEventListener('DOMContentLoaded', () => {
      const form = document.getElementById('myForm');
      const status = document.getElementById('status');

      async function handleSubmit(event) {
        event.preventDefault();
        status.textContent = 'Submitting...';

        // Simulate an asynchronous operation (e.g., network request)
        await new Promise((resolve) => setTimeout(resolve, 2000));

        status.textContent = 'Form submitted successfully!';
      }

      // Add an async event listener
      eventManager.add(form, 'submit', handleSubmit, { async: true });
    });
  </script>
</body>
</html>

Explanation

  • The handleSubmit function is asynchronous and simulates a network request.
  • The async option ensures that any errors in the async function are caught and can be handled appropriately.

5. Error Handling with onError

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>EventListenerManager - Error Handling Example</title>
</head>
<body>
  <button id="errorButton">Click Me</button>
  <div id="errorMessage" style="color: red;"></div>

  <!-- Include the EventListenerManager script -->
  <script src="EventListenerManager.js"></script>
  <script>
    document.addEventListener('DOMContentLoaded', () => {
      const button = document.getElementById('errorButton');
      const errorMessage = document.getElementById('errorMessage');

      function handleClick() {
        // Simulate an error
        throw new Error('Something went wrong!');
      }

      function handleError(error) {
        errorMessage.textContent = `Error: ${error.message}`;
      }

      // Add event listener with error handling
      eventManager.add(button, 'click', handleClick, { onError: handleError });
    });
  </script>
</body>
</html>

Explanation

  • When the button is clicked, the handleClick function throws an error.
  • The onError handler catches the error and displays an error message to the user.

6. Attaching Metadata to Events

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>EventListenerManager - Metadata Example</title>
</head>
<body>
  <button id="metaButton">Click Me</button>

  <!-- Include the EventListenerManager script -->
  <script src="EventListenerManager.js"></script>
  <script>
    document.addEventListener('DOMContentLoaded', () => {
      const button = document.getElementById('metaButton');

      function handleClick(event) {
        if (event.metadata) {
          console.log('Event ID:', event.metadata.eventId);
          console.log('Timestamp:', new Date(event.metadata.timestamp));
          console.log('Original Callback:', event.metadata.originalCallback);
        }
        alert('Button clicked!');
      }

      // Add event listener with metadata
      eventManager.add(button, 'click', handleClick, { metadata: true });
    });
  </script>
</body>
</html>

Explanation

  • The handleClick function accesses metadata attached to the event object.
  • This can be useful for logging or debugging purposes.

7. Using once() for One-Time Event Listeners

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>EventListenerManager - Once Example</title>
</head>
<body>
  <button id="onceButton">Click Me Once</button>

  <!-- Include the EventListenerManager script -->
  <script src="EventListenerManager.js"></script>
  <script>
    document.addEventListener('DOMContentLoaded', () => {
      const button = document.getElementById('onceButton');

      function handleClick() {
        alert('This will only appear once!');
      }

      // Add a one-time event listener
      eventManager.once(button, 'click', handleClick);
    });
  </script>
</body>
</html>

Explanation

  • The handleClick function will only be called once, after which the event listener is automatically removed.

8. Automatic Cleanup with addWithCleanup

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>EventListenerManager - Cleanup Example</title>
</head>
<body>
  <button id="cleanupButton">Click Me</button>
  <button id="removeListenerButton">Remove Listener</button>

  <!-- Include the EventListenerManager script -->
  <script src="EventListenerManager.js"></script>
  <script>
    document.addEventListener('DOMContentLoaded', () => {
      const clickButton = document.getElementById('cleanupButton');
      const removeButton = document.getElementById('removeListenerButton');

      function handleClick() {
        alert('Button clicked!');
      }

      // Add event listener with cleanup
      const cleanup = eventManager.addWithCleanup(clickButton, 'click', handleClick);

      // Remove the event listener when the remove button is clicked
      removeButton.addEventListener('click', () => {
        cleanup();
        alert('Event listener removed');
      });
    });
  </script>
</body>
</html>

Explanation

  • The addWithCleanup method provides a convenient way to remove event listeners without tracking the eventId.
  • Clicking the "Remove Listener" button calls the cleanup function, removing the event listener from the "Click Me" button.

9. Combining Debounce and Async Callbacks

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>EventListenerManager - Debounce and Async Example</title>
</head>
<body>
  <input type="text" id="searchInput" placeholder="Type to search..." />
  <div id="results"></div>

  <!-- Include the EventListenerManager script -->
  <script src="EventListenerManager.js"></script>
  <script>
    document.addEventListener('DOMContentLoaded', () => {
      const input = document.getElementById('searchInput');
      const results = document.getElementById('results');

      async function handleInput(event) {
        const query = event.target.value;
        if (!query) {
          results.textContent = '';
          return;
        }
        results.textContent = 'Searching...';

        // Simulate an asynchronous search operation
        await new Promise((resolve) => setTimeout(resolve, 1000));

        results.textContent = `Results for "${query}"`;
      }

      // Debounce the async input handler
      eventManager.add(input, 'input', handleInput, { debounce: 500, async: true });
    });
  </script>
</body>
</html>

Explanation

  • This example demonstrates combining debouncing with an asynchronous callback.
  • The search operation is debounced to reduce unnecessary function calls and handle asynchronous operations smoothly.

10. Throttling with noLeading and noTrailing Options

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>EventListenerManager - Throttle Options Example</title>
  <style>
    body {
      height: 2000px;
    }
    #scrollInfo {
      position: fixed;
      top: 10px;
      left: 10px;
      background: rgba(255, 255, 255, 0.8);
      padding: 5px;
    }
  </style>
</head>
<body>
  <div id="scrollInfo">Scroll Y: 0</div>

  <!-- Include the EventListenerManager script -->
  <script src="EventListenerManager.js"></script>
  <script>
    document.addEventListener('DOMContentLoaded', () => {
      const scrollInfo = document.getElementById('scrollInfo');

      function handleScroll() {
        scrollInfo.textContent = `Scroll Y: ${window.scrollY}`;
      }

      // Throttle with no leading call
      eventManager.add(window, 'scroll', handleScroll, {
        throttle: 200,
        noLeading: true,
      });

      // Uncomment the following code to throttle with no trailing call
      /*
      eventManager.add(window, 'scroll', handleScroll, {
        throttle: 200,
        noTrailing: true,
      });
      */
    });
  </script>
</body>
</html>

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

I welcome contributions from developers of all experience levels. If you have an idea, found a bug, or want to improve something, I encourage you to get involved!

How to Contribute

  1. Read Contributing Guide for details on how to get started.
  2. Fork the repository and make your changes.
  3. Submit a pull request, and we’ll review it as soon as possible.

License

MIT License

Avati is open-source and distributed under the MIT License.


Follow on Twitter Follow on LinkedIn Follow on Medium Made with ❤️ Star on GitHub Follow on GitHub