Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

is there a reasonable concept of using WeakRef for listeners? #274

Open
christopherreay opened this issue Mar 19, 2021 · 2 comments
Open

Comments

@christopherreay
Copy link

So if we add a listener using a WeakRef option, then the listener function will not be called and will be automatically removed from the listener list?

Would probable require some kind of checks when determining if to send the event to the listener

Should work generically for all types of listeners, sync and async etc.

What do you think about this? Does it make sense?

@DigitalBrainJS
Copy link
Collaborator

@christopherreay Are you talking about introducing a WeakMap instead of a plain object to store event handlers for the potential ability to auto-dispose of listeners?
If so, this won't work at all. WeakMap requires object keys since primitive types can't have a reference that could be 'weak'. So in this case we can't fire an event by its name (a plain string), because the event name must be an object reference, and this reference we will have to store somewhere to be able to handle events. Moreover, we will have to control its value manually to be garbage collected and can't iterate over its elements. In other words, WeakMaps is not suitable for this task.

//pseudo-code
let event= {}; //event reference;

const ee= new EventEmitter();

const handler= ()=> console.log('hello1');

ee.on( event, handler);

ee.off( event, handler); // we can't iterate over WeakMap elements, so handlers are still stored in the array data structure.

ee.on( event, ()=> console.log('hello2'));

ee.fire(event, 123);

// event= null; // Where we should do this?

// what about exporting event 'names' to be handled from outside? Where and how it can be set to null?
module.exports= {
  readyEvent: event; ??? // reference leakage
}

@christopherreay
Copy link
Author

christopherreay commented Mar 21, 2021 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants