Reputation: 67
Might be a simple question, but I have an event, lets call it addObject
. I emit this event and I have two listeners for it. One listener requires an "important object" const to be passed through but the other does not. So I have something like
myFunction1() {
const importantObject = {...};
// other logic
this.emit('addObject');
this.emit('addObjectWithParam', importantObject);
}
myFunction2() {
//other logic
const forceUpdate = this.forceUpdate.bind(this);
this.addListener('addObject', forceUpdate);
}
myFunction3() {
this.addListener(
'addAuditTest',
this.handlerFunction.bind(this),
);
}
It seems like breaking an abstraction barrier by emitting 'addObject' twice, but I do this, because forceUpdate()
takes no parameters, but I need importantObject
in handlerFunction()
.
What is the cleanest thing to do here/best practices?
Upvotes: 0
Views: 279
Reputation: 778
This is more of a higher level question but I will try to answer as best as I can.
Simply the question that I would ask myself is from "business" or "domain" perspective are they the same event or not.
In terms of events / event handling it shouldn't matter whether a listener needs the arguments of an event. What matters is what the events themselves are.
Take an example of an event onSelect
. Now this event will happen every time a user changes a dropdown field. It will pass through the new value that the user has selected.
I have two consumers:
In this case if a consumer doesn't care they simply ignore the argument. We don't have to provide different events for the same onSelect
.
However, you need to make sure they really are the same. Another example is that of onMouseUp
vs onClick
.
The onClick
event may not have an argument as it's simply informing that the user has clicked a button. Where as the onMouseUp
might have information about the mouse location or what not.
They can both be used to detect a click but they are fundamentally different events.
You just need to figure out if they are the same event with different consumer needs or the same event.
Upvotes: 1