Developing custom events in an NPM package

Developing a basic npm package with signalr integration has been my recent project. Here's how it works:

  • First, the user installs the package
  • Then, the package establishes a connection using signalr
  • At a certain point, the server triggers a function and transmits data through it
  • The user needs to be able to “listen” and await this incoming data

Here's what I envision the user doing:

myPackage.on(“dataInTheHouse”, (data) => {
const myData = data;
});

Something along those lines...

I attempted to use an npm package called “event-emitter” for this purpose, but struggled to create a dynamic function for all events and ended up feeling overwhelmed.

How can I overcome this challenge and achieve the desired functionality?

Answer №1

Update on the answer:

I successfully implemented this solution in my project. (I opted for typescript while developing it):

To start, you must declare a new variable. Here's an example:

events = new EventEmitter();

Then, Within the function called by the server, I included the following:

this.events.emit(“dataInTheHouse”, “This is the data we received!”);

The user of my package can easily utilize it like so:

this.myPackage.events.on(“dataInTheHouse”, (data) => console.log(data));

It couldn't be simpler.

If you want to delve deeper into the topic, I came across this helpful resource: https://css-tricks.com/understanding-event-emitters/

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

Unable to execute Protractor using Node.js command line

Hi there! Currently, I am in the process of setting up protractor for the very first time using Node.js. I found detailed instructions on how to do this on the AngularJS website under the section "Running E2E Tests": https://docs.angularjs.org/tutorial Ho ...

The useEffect hook in ReactJs is triggering multiple times

Encountering challenges while developing an Infinite scroll using ReactJs and Intersection observer API. Upon initial application load, the API gets called twice instead of once. This behavior may be due to strict mode, although not confirmed. Additionall ...

Value in Hook not updating after memoization of parent component

Let's consider this scenario: import * as React from "react"; const useMyHook = ({ element }: { element: HTMLElement | null }) => { React.useEffect(() => { if (element) { console.log("element in hook", element); ...

I'm at a loss with this useState error, can't seem to figure

Could you please help me understand what is incorrect in this code snippet? import React, { useState } from 'react'; import UsrInput from '../component/UsrInput' import TodoItemList from '../component/TodoItemList' const ...

Neglecting the Outcome of Async/Await

I am facing an issue where I need to send different SMS messages to different recipients synchronously, but my current implementation using async/await is not producing the expected results. Below is the code snippet causing the problem: Upon querying fo ...

Are you facing issues with Handlebars parsing?

I am struggling to identify the issue in my HTML/JS code. Here is my HTML/JS: <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <script src="handlebars-v1.1.2.js"> ...

NPM package's Redux store

I've developed a react npm package with a redux store and have another react redux application. By importing the npm package, I now have two redux stores - one from the package and one from the importing application. However, when trying to access the ...

Is it possible to define a Divider or Header within the options array for the dropdown component in Semantic UI React?

Currently, I'm incorporating ReactJS along with SemanticUI for ReactJS to enhance the appearance of my front end. My query pertains to whether it is feasible to define a header or divider within the options array of objects for a dropdown component? ...

Is there a method to compile C++ code in advance for integration into node-red?

I am currently developing a C++ interface code library for a device that operates using a proprietary protocol. Due to confidentiality reasons, I am unable to disclose the specifics of the protocol, however, I can share the compiled library without revea ...

An error occurred when attempting to hide or show a jQuery loading animation

Here is the HTML code I am using: <div id="success_message" style="display:none"> <p>Good job!</p> </div> <div id="my-form"> <form> <input>....... (lots of inputs) <input id="my-btn" ...

unable to effectively test promises with stubs using nodejs mocha

Currently, I am facing a couple of challenges when attempting to perform unit testing on promises using Mocha. 1) The main issue I encounter is an Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Prom ...

Having trouble establishing a connection with mongoose and typescript

When attempting to establish a connection using mongoose, I consistently encounter the errors outlined below. However, if I use MongoClient instead, everything functions as expected. import connectMongo from '../../lib/connectMongo' console.log( ...

Ways to simulate a dependent class in TypeScript & JEST without modifying constructor parameters to optional

Currently, I am attempting to replicate a well-known process in Java development using TypeScript and JEST for practice. In this scenario, there is a Controller class that relies on a Service class. The connection between the two is established through the ...

Progress Bars Installation

For more detailed information, visit: https://github.com/rstacruz/nprogress After linking the provided .js and .css files to my main html file, I am instructed to "Simply call start() and done() to control the progress bar." NProgress.start(); NProgress. ...

Two Ajax Requests Simultaneously

I am currently faced with the challenge of handling two requests simultaneously. The first request involves executing a lengthy PHP script that takes 10 minutes to complete (I cannot modify it using JavaScript, so that's not an option). The second ...

Exploring the possibilities of utilizing JavaScript within TypeScript

My dynamic javascript object holds all the resources (translation strings) for my app. Here's how it is structured: var ResourceManager = (function () { function ResourceManager() { var currentLanguage = $('#activeLanguage').htm ...

Using JSON with PHP to send data and receiving the response back with JavaScript

Despite exploring numerous questions and attempting various methods, I have been unable to find a solution that works. Here is my JavaScript file: function sendData() { var jsondata; var j = {"pub_id":"'+pid+'","a_type":"'+a_t&ap ...

The error message "NullInjectorError: No provider for HTTP!" is generated by the ionic-native/http module

Currently working with ionic 3.2 and angular. To install the HTTP module (https://ionicframework.com/docs/native/http/), I used the following commands: ionic cordova plugin add cordova-plugin-advanced-http npm install --save @ionic-native/http In my scri ...

What is the hostname that npm install directs to?

My task is to set up multiple Node.js packages using npm on a standalone server that does not have direct internet access. I am able to specify an IP Address and port for access. When executing 'npm install' from the command line, where can I f ...

I could use some assistance with iterating through an array that is passed as a parameter to a function

Compute the product of parameter b and each element in the array. This code snippet currently only returns 25. This is because element a[0], which is "5", is being multiplied by argument b, which is also "5". The desired output should be ...