xShirase
xShirase

Reputation: 12399

Node.js listen to events on dynamically created objects

I have a Node.JS application which dynamically creates Record objects from info stored in a db, each instance of Record emits events, and I'd like to listen to them all. It goes like this :

db.getRecords(function(group){
    for (var i = 0; i < group.length; i++) {
        var record = new Record(JSON.parse(group[i].list),group[i].id,group[i].time);
        record.setup();
        record.on('dropped',function(){
            db.deleteRecord(record.id);
        });
    }
});

The code above will always listen to the events emitted by the last object created... It makes sense but I can't figure out how to listen to all my Record objects, and react to the evants they emit. Anhy help/suggestions would be appreciated!

Upvotes: 0

Views: 800

Answers (1)

Louis
Louis

Reputation: 151411

Your current code is listening to the events generated by all your records. However, db.deleteRecord will be called, in all cases, with the id of the last record covered by your loop. To take a specific instance, the event handler for the first record will call db.deleteRecord with the id of the last record.

To fix this, you could do:

record.on('dropped',function(id){
    db.deleteRecord(id);
}.bind(undefined, record.id));

This will force the id passed to your callback to be set to the value that record.id has at the time bind is called. (The first argument to bind sets this to undefined inside the anonymous function.)

Upvotes: 3

Related Questions