简体   繁体   English

如何在node.js中获得实例名称

[英]How to get the NAME OF an INSTANCE in node.js

I have build a class "Queue" in node.js. 我已经在node.js中建立了一个类“ Queue”。 I need some queues, so i make instances like "orderQueue": var orderQueue = new queue(); 我需要一些队列,因此需要创建类似于“ orderQueue”的实例: var orderQueue = new queue(); .

When the last element in a queue was processed, the queue should emit a signal like "orderQueue-processed" process.emit(instance.name + "-processed"); 处理队列中的最后一个元素时,该队列应发出类似“ orderQueue-processed” process.emit(instance.name + "-processed"); , which should be handled by my main program process.on(myobject.name + "-processed", function(){ addmorework ();}); ,应由我的主程序process.on(myobject.name + "-processed", function(){ addmorework ();});

But up to now i have not found out how i can get the name of the instance . 但是到目前为止,我还没有找到如何获取实例名称的方法 Answers in stackoverflow do something with the window object, but it's not a bowser, it's node.js. stackoverflow中的答案对window对象有作用,但它不是Bowser,而是node.js。

May be the idea to use the name is not good. 可能是使用名称的想法不好。 A recommendation what to use instead and is easy to handle would be also very welcome. 也将非常欢迎提出建议,使用什么代替并且易于处理。

There are two possible approaches to this that don't involved the name of the queue. 有两种不涉及队列名称的可能方法。

  1. have your queue object act as an EventEmitter , so your main program creates instances of the queue, and then registers an event listener on it: 让您的队列对象充当EventEmitter ,因此您的主程序创建队列的实例,然后在其上注册一个事件侦听器:

     var orderQueue = new queue(); queue.on("processed", function() { // Do something when this specific queue has been emptied }); 
  2. Or, pass the object object as the event data: 或者,将对象对象作为事件数据传递:

     process.emit("processed",instance); 

    so the event listener is given the queue that emitted the event. 因此,事件监听器被赋予了发出事件的队列。

You can just assign the queue a name when you create it and then the queue will store the name as an instance variable: 您可以在创建队列时为其分配名称,然后该队列会将其存储为实例变量:

function queue(name) {
    this.name = name;
    // other constructor code
}

var orderQueue = new queue("orderQueue");.

Then, when the last element in the queue is processed by a method on the queue, you can just get the name from the instance data for the queue: 然后,当队列中的方法处理了队列中的最后一个元素时,您只需从队列的实例数据中获取名称:

process.emit(this.name + "-processed");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM