Tips for triggering an event from a function instead of the window

Everything is functioning as expected, with the event listener successfully capturing the custom event when it is dispatched from the window and listened for as loading, all seems to be working well.

const MyLib = mylib();
  function mylib() {
    const res = {
      init: (data) => {
        let loading = new CustomEvent('loading', {detail: { loading: true }});
        window.dispatchEvent(loading);
      }
    }
  return res;
}

event listener

 window.addEventListener('loading', handleLoading);

I'm looking to update it to use MyLib.addEventListener instead of window.addEventListener.

Additionally,

window.dispatchEvent(loading); should become MyLib.dispatchEvent(loading);

However, when attempting this change, I encounter an error message stating

TypeError: MyLib.addEventListener is not a function

The solution posted below involves using a class, but I am curious if it is possible to achieve this without utilizing a class structure.

Answer №1

To effectively handle events on an object, the object must inherit from the EventTarget interface.

class MyLibrary extends EventTarget {
    constructor() {
        super();
    }

    initialize(data) {
        let loadingEvent = new CustomEvent('loading', { detail: { loading: true } });
        this.dispatchEvent(loadingEvent);
    }
}

// Assume myLibrary is an instance of MyLibrary

useEffect(() => {
    myLibrary.addEventListener('loading', handleLoading);
    return () => {
        myLibrary.removeEventListener('loading', handleLoading);
    };
}, []);

Answer №2

Using a Proxy object can help meet the specifications.

This code snippet demonstrates how the original MyLib object is encapsulated within a Proxy. The get trap of the Proxy is triggered when accessing methods like addEventListener or dispatchEvent.

function mylib() {
  const res = {
    init: (data) => {
      let loading = new CustomEvent('loading', {detail: { loading: true }});
      MyLib.dispatchEvent(loading);
    }
  }
  return res;
}

const MyLib = new Proxy(mylib(), {
  get: function(target, prop) {
    if (prop === `addEventListener`) {
      return (...args) => window.addEventListener(...args);
    } 
    if (prop === `dispatchEvent`) {
      return (...args) => window.dispatchEvent(...args);
    }
    return target[prop];
  }
});

MyLib.addEventListener('loading', () => { console.log("Hello world !!!") });
MyLib.init();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

underscore.js does not allow data to be manipulated outside of the _.each

Struggling to get my head around utilizing the underscore loop in jQuery's $.ajax function for retrieving a JSONp file... Within the success section, I have the following code snippet: success : function(response) { var dataResp = '' ...

AngularJS: Recommendations for structuring code to dynamically update the DOM in response to AJAX requests

Within Angular's documentation, there is a straightforward example provided on their website: function PhoneListCtrl($scope, $http) { $http.get('phones/phones.json').success(function(data) { $scope.phones = data; }); $scope.order ...

Is there a way to conditionally redirect to a specific page using NextAuth?

My website has 2 points of user login: one is through my app and the other is via a link on a third-party site. If a user comes from the third-party site, they should be redirected back to it. The only method I can come up with to distinguish if a user is ...

Restore the button to its original color when the dropdown menu is devoid of options

Is it possible to change the button colors back to their original state automatically when a user deselects all options from my dropdown menu? The user can either uncheck each option box individually or click on the "clear" button to clear all selections. ...

Retrieving Values from Array with AngularJS Keys - A How-To Guide

I need to access a specific value from a key inside an array, like this: $scope.result = [ { "key":"logo_big", "value":"/assets/images/aaa.jpg" }, { "key":"logo_small", "value":"/assets/images/logo94x57Bis.png" }, { ...

What steps can I take to ensure TypeScript compiler approves of variance in calling generic handlers, such as those used in expressJS middleware?

disclaimer: I am a bit uncertain about variance in general... Here is the scenario I am facing: // index.ts import express from 'express'; import {Request, Response} from 'express'; const app = express(); app.use(handler); interface ...

Is there a way to detect and intercept M-SEARCH requests in Express?

Here is my Express program designed to capture M-SEARCH requests: router['m-search']('/', function(req, res, next) { res.send('Received an M-SEARCH request\n'); }); This code specifically responds to the following r ...

A guide on verifying the static characteristics of a class with an interface

When it comes to converting a constructor function in JavaScript to TypeScript, there are some important considerations to keep in mind. function C() { this.x = 100; } C.prototype = { constructor: C, m() {} }; C.staticM = function () {}; Here ...

Having trouble getting your Ajax script to function correctly when submitting a form?

I am currently facing an issue where I am loading a partial page, but I do not want the form on this page to redirect when the save button is clicked. I am unsure if I am using the script correctly. I would like to post to the controller when the submit b ...

Executing a function after a subscriber has finished in Angular 8+

Welcome fellow learners! Currently, I am diving into the world of Angular and Firebase. I am facing an interesting challenge where I fetch ticket data from my collection and need to add new properties to it. However, the issue arises when my ordering funct ...

Changing Image Size in Real Time

Trying to figure out the best way to handle this situation - I need to call a static image from an API server that requires height and width parameters for generating the image size. My website is CSS dynamic, adapting to different screen sizes including ...

Executing child processes in the Mean Stack environment involves utilizing the `child_process`

I am working on a Mean application that utilizes nodejs, angularjs and expressjs. In my setup, the server is called from the angular controller like this: Angular Controller.js $http.post('/sample', $scope.sample).then(function (response) ...

The getElementByID function will return null in this instance, as it has not been loaded

Hello everyone, I am facing an issue while trying to access an element by its ID in JavaScript as it keeps returning null. This problem arises because the element is not fully loaded when the DOM is initially created, due to a plugin called Restrict Conte ...

Toggle the visibility of a div based on the id found in JSON data

I am looking to implement a JavaScript snippet in my code that will show or hide a div based on the category ID returned by my JSON data. <div id="community-members-member-content-categories-container"> <div class="commun ...

What is the best way to validate if fields are blank before sending a message using the button?

<template> <div> <div class="form-group"> <label for="name">First Name</label> <input type="text" class="form-control" v-model="firstName" placeholder="Ente ...

Random Angular template string that does not contain a templateRef

Could a string retrieved from an external resource, such as an http response, be passed as a dynamic template that binds to the component's instance without relying on TemplateRef? Context: Consider having an AppComponent with at least one variable n ...

What is the best way to extract data from multiple FormControl instances using RxJS in Angular?

I am currently subscribed to three FormControl instances named filter1, filter2, and filter3. My goal is to fetch the values of all three whenever any one of them changes. I initially attempted to achieve this using combineLatest, but found that it only em ...

What are some ways I can customize the appearance of this Google Maps infoWindow?

I was able to create a Google Maps script using JavaScript code. The map displays multiple locations with corresponding latitude and longitude coordinates. This script can be viewed at . My objective now is to customize the appearance of the info windows ...

Execute the function within setInterval only one time

I have a setInterval function that calculates the time difference between a specified date and the current time. Once this difference is less than an hour, I want to execute some code only once. const countdownDate = new Date('March 15, 2021 11:30:00& ...

ExtJS variable not populating with servlet data

I'm facing an issue with my code where I am calling a servlet from JavaScript using an AJAX request. The data from the servlet is shown in a message box within the success function, but it's not being loaded into a variable called `myData` in Jav ...