Can JavaScript Classes Trigger Events?

I'm feeling a bit confused. I am working on creating a class that performs certain actions, and at a specific point in the process, I need to trigger an event to indicate completion. However, I can't seem to find information on how to implement events in JavaScript. Can someone provide some insight on this matter?

class MyClass {
    constructor() {}

    test() {
       // Do Stuff
       // TRIGGER EVENT: onTest
    }
}

-------------------------
script.js
-------------------------
let myClass = new MyClass();

// How do I register the event listener here?
// myClass on event onTest () = {dostuff;}

myClass.test();

Answer â„–1

If you want to, you can utilize the pre-existing events and attach them to the document, then simply employ addeventlistener for that specific event.

https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events

class MyClass {
    constructor() {}

    test() {
       document.dispatchEvent(new Event('tested'));
    }
}

let myClass = new MyClass();

document.addEventListener('tested', function (e) { console.log("tested!") }, false);

myClass.test();

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

Is it possible to incorporate faces from an array into a THREE.BufferGeometry?

My task is to create a Mesh using a BufferGeometry. Right now, my geometry is handled by a worker. Worker: To begin with, I start by creating a Three.Geometry and then proceed to build my bufferGeometry before sending the data back to the main thread. 1. ...

Encountering silence: React JS fetch call left unanswered by Sinatra server

Exploring the realms of Sinatra and React JS, I am venturing into making a GET call from my React website to a Sinatra server in order to display plain text. The Sinatra Server script: require 'sinatra' set :root, 'lib/app' before d ...

Troubleshooting issue with Angular's inability to loop through a multi-dimensional JSON

I recently started experimenting with Angular and decided to create a shopping cart application. I found a pre-made site template that organizes items into categories using the following structure: <div class="row"> <ul> <li>item1</li ...

retrieve the timestamp when a user initiates a keystroke

Seeking assistance from the community as I have been struggling with a problem for days now. Despite searching on Google and Stack Overflow, I haven't found a solution that works for me. My web application features an analog clock, and I need to capt ...

Exploring the process of retrieving data from localStorage in Next.js 13

Having recently delved into the realm of Next JS, I've encountered a hurdle when it comes to creating middleware within Next. My aim is to retrieve data from local storage, but I keep hitting roadblocks. middleware.ts import { key, timeEncryptKey, to ...

AngularJS Integration with Google OAuth2 using Devise for Seamless Sign-in

Just like the scenario described in this post, our team is currently utilizing the Google JavaScript API for OAuth2 authentication.... Our next step involves signing in the user to our Rails server. Given that we are using Devise, it seems that invoking D ...

Checking password fields in Angular upon submission or when they have been edited

i created a controller and form with validation rules, but i'm struggling to ensure that the confirm_password matches the password? html <div class="col-md-5" ng-controller="RegisterController as vm"> <form id="sign_up" name="SignUp" ng ...

What is the best way to obtain a public constant from an object?

Whenever I perform the following actions Txtbin a; switch(err){ case a.ERR_EMPTY_IMAGE: std::cerr << "Error: Image is empty\n" << std::endl; break; } An error message is displayed saying txtbin.cpp: In function †...

Speed up - Handle alias resolution with module federation

Currently import federation from '@originjs/vite-plugin-federation'; import react from '@vitejs/plugin-react-swc'; import dns from 'dns'; import path from 'path'; import { visualizer } from 'rollup-plugin-visual ...

Obtaining a Buddypress user's name through a JavaScript file

When working with my buddypress PHP templates, I typically fetch the username of a user using their ID like this: <?php echo bp_core_get_username( '{{userID}}' ) ?> However, I now need to access the username from an external JavaScript fi ...

Remove the initial section of the text and provide the rest of the string

I am a beginner in the world of Javascript and unfortunately I have not been able to find an answer to my current problem. Here is the situation. On a webpage, I am receiving a URL that is sometimes presented in this format: http://url1.come/http://url2.c ...

Improving react-google-markers with a new search filtering system

In my controlled component, I have a list of markers and an input field for searching within that list. Concurrently, there is a map component adjacent to the marker list component. While the search functionality updates the marker list appropriately, the ...

How can you tell when directionsService has finished processing and returned its status?

Within the code snippet below (keep an eye on the error console!), I am rapidly querying Google Maps for ten different locations to determine whether it can calculate a route to them or not. While this method does work, I require the result from Google to ...

establish a preset selection as checked if the countryCode indicates the United States

Is there a way to automatically set the default checked value of Fitting to 'US' when the countryCode =='US' in this scenario? Here is the code snippet: export default function ProductOptionsDefault({ name, values, countryCode, } ...

Show/Hide All Actions in a Vue.js table using Bootstrap styling

In my Vue.js project, I created a bootstrap table to display data loaded from local JSON files. One of the features I added is the ability to Show/Hide details of specific rows, which shows a full message for that row. Now, I'm looking for a way to im ...

A Smarter Approach to Updating Text Dynamically with JavaScript and Vue

Currently, I am utilizing Vue to dynamically update text by using setInterval() in combination with a data property. The method I have in place is functional, but I am curious if there exists a more efficient way to optimize it. Is the current code as stre ...

Turning off the AngularJS dropdown multiselect functionality

I need a directive that can disable the dropdown multiselect in AngularJS. It's currently functioning properly when the checkbox is changed, but it's not working when the controller initializes. I want the dropdown to be disabled based on the val ...

Unable to access account: HTML Javascript login issue

Problem with Login Code As a newcomer to HTML, CSS, and almost unknown in Javascript, I sought help from others to create a login code. The code was working fine earlier, but now it's not functioning as expected. Despite checking everything, I can&ap ...

NodeJS API integration failure during ReactJs login attempt

Currently, I am tackling a small project on implementing user login functionality in ReactJs with Nodejs and Express-session. The issue I am facing is that my front end (React login page) isn't functioning properly. Below is the Fetch API code snippet ...

Starting up various modules in Angular 6 using arrays

Can an array be declared and used to bootstrap multiple components in module.ts? I attempted the following: export var initialComponents = []; initialComponents.push(AppComponent); if(condition) { initialComponents.push(IchFooterComponen ...