Reputation: 281
I have three functions: A, B and C. A needs to run B to work. C needs to be run on A sometimes, but isn't always there. Is it correct practice to use events in the case of function c? If not, what would be correct practice. Finally, are events notably slower/less reliable than standard calls?
function a() {
//Do stuff
b();
alert([Var]);
var event = new Event('a');
document.dispatchEvent(event);
}
function b() {
var Var = "a ran";
}
document.addEventListener('a',function c() {
console.log("a ran");
}, false);
Upvotes: 1
Views: 57
Reputation: 7591
The downside with using events, and you notice this more in Class based languages like Swift or Java, is that the code is harder to follow. If you just send out an event, you can't see directly—in the code—which functionalities that you will affect, if the code belongs to a huge project.
If you split up your code in different files, which you will do if you're using a framework, it's also hard to see what triggers method C
just by looking at the code.
I personally try to design the most readable code possible, but that's just a choice of mine. I try to avoid events if I can, but by using mainly Polymer, it's an impossible task. :) We do try to restrict events to only use them if they belong to a specific functionality, like handling account information, where the name of the event strictly says which behavior ("class") it comes from.
Upvotes: 0
Reputation: 18859
I don't remember where, but I have read an interesting metaphor on event driven programming.
On a basketball field, there are multiple ways to keep the scoreboards.
When the ball goes through the ring, the ball could update all the scoreboards by sending a message to each of them.
However, it is much more interesting for the scoreboards to subscribe to the event.
This way, the ball does not care about how many listeners there are, it just needs to emit the event.
Event driven programming is a choice.
You can either create a condition in function c, or in function a from which you could call function c.
I think that it depends on the context; keeping in mind the story of the basketball gives you the context that you need to make your own decision.
Document events would logically be slower but I haven't seen any benchmarks.
If you don't overcrowd the page with event listeners, I don't believe that it will be a problem.
Upvotes: 1