简体   繁体   中英

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

I have build a class "Queue" in node.js. I need some queues, so i make instances like "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"); , which should be handled by my main program 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.

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:

     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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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