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

799 views Asked by At

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.

2

There are 2 answers

0
knolleary On

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.

2
jfriend00 On

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