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

Design problem #146

Closed
gevorgter opened this issue Jul 25, 2021 · 3 comments
Closed

Design problem #146

gevorgter opened this issue Jul 25, 2021 · 3 comments

Comments

@gevorgter
Copy link

gevorgter commented Jul 25, 2021

There is a bit of "design" problem that makes this not usable.

  1. You can not remove arrow function which is understandable but takes you to the actual problem if you want to be able to call .off method.
  2. The handler function is not passed event_type as parameter. So I can not have the same handler for multiple events.

Real life example: I have several fields i need to get events from. Do not want to use .all in this case.

for (let i = 0; i < fields.length; i++)
emitter.on('updated_' + fields[i], ReCalculate);

function ReCalculate(val) {
..do not know which field was undated. Only have it's new value
}


The issue could have been easily solved with arrow function but then i can never remove it.
Also just have .on method return fn it got as a parameter. That way i can unsubscribe arrow functions as well.

@developit
Copy link
Owner

Why can't you give your arrow function a name?

for (let i = 0; i < fields.length; i++) {
  const field = fields[i];
  const fn = (val) => {
    console.log(field, val);
    emitter.off('updated_' + field, fn);
  };
  emitter.on('updated_' + field, fn);
}

@gevorgter
Copy link
Author

I see what you saying, I do need to remove them at some point. So instead of relying on .on returning fn. I can take them from your loop.

thanks.
It would have been prettier if .on returned 'fn' that was passed to it.

@developit
Copy link
Owner

Just to close this out: wildcard event listeners do receive the type as their first argument:

emitter.on('*', (type, val) => {
  console.log(type, val);  // ["updated_foo", "bar"]
});

emitter.emit('updated_foo', 'bar');

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