[英]Creating NPM Package custom events
I'm building a simple npm package using signalr. The flow is this:我正在使用 signalr 构建一个简单的 npm package。流程是这样的:
I expect the user to do something like:我希望用户做类似的事情:
myPackage.on(“dataInTheHouse”, (data) => {
const myData = data;
});
More or less...或多或少...
I tried using npm package called “event-emitter”, but couldn't understand how to make dynamic function for all events, and honestly got a bit confused.我尝试使用 npm package 称为“事件发射器”,但无法理解如何为所有事件制作动态 function,老实说有点困惑。
What should I do to achieve this?我应该怎么做才能实现这一目标?
Answer update:答案更新:
I managed to do it the following way.我设法通过以下方式做到了。 (I wrote my package using typescript by the way):
(顺便说一句,我使用 typescript 写了我的 package):
You need to declare a new variable.您需要声明一个新变量。 For example:
例如:
events = new EventEmitter();
And then, Inside the function the server invokes, I wrote the following:然后,在服务器调用的 function 中,我写了以下内容:
this.events.emit(“dataInTheHouse”, “This is the data we got!”);
And the consumer of my package can just use:而我的 package 的消费者可以使用:
this.myPackage.events.on(“dataInTheHouse”, (data) => console.log(data));
Easy as that.就这么简单。
For further reading, I found this solution here: https://css-tricks.com/understanding-event-emitters/为了进一步阅读,我在这里找到了这个解决方案: https://css-tricks.com/understanding-event-emitters/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.