Skip to content
This repository was archived by the owner on Apr 22, 2023. It is now read-only.
This repository was archived by the owner on Apr 22, 2023. It is now read-only.

events: shared object references are emitted to listeners #25466

@samhmills

Description

@samhmills

When emitting to multiple listeners for the same event type, the for
loop iteration over these listeners shares the same arguments. This
means (for objects), the copy is only shallow, and changes made by one
listener are overwritten on the object for the next listener.

For example, if we pass an object with arrays: as below

EventEmitter.emit("event", {
  data: [{
      users: [9237895]
  }]
});

And the first listener sets the users array as null like so:

EventEmitter.on('event', function(packet) {
    var data = packet.data[0];
    data.users = null;
});

The second event listener will ALWAYS show the array as null. This is
because only a shallow copy of the arguments is made and not a deep
copy.

Here is the full code snippet that will reproduce the issue predictably:

var EventEmitter = require('events').EventEmitter;
var EE = new EventEmitter();

console.log("starting")

EE.on('event', function(packet) {
    //console.log(packet); //Log pre to see that it is not null
    var data = packet.data[0];
        data.users = null;  
});

EE.on('event', function(packet) {
    console.log(packet.data[0]); //packet.data[0].users will equal null.
});


setInterval(function(){
    console.log("emitting");
    EE.emit("event", {
        data: [
            {
                users: [9237895] //This outputs as null on the second event listener;
            }
        ]
    });
}, 5000)

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions