Why use event listeners over function calls?

I’ve been studying event listeners lately, and I think they’ve finally been removed. Basically, these are functions called by another method of the object. My question is: why create an event listener when calling a function, will it work fine?

For example, I want to call player.display_health (), and when this is fired, the player.get_health () method must be started and saved so that display_health () has access to it. Why should I use an event listener to simply call a function? Even if display_health () was in another object, this still doesn't seem to be a problem for me.

If you have another example that is better for use, let me know. Perhaps specific languages ​​cannot take so many benefits from this? (Javascript, PHP, ASP?)

+9
source share
5 answers

You cannot always control the code making the call. Or even if it is, you do not want to inject dependencies in this code. In such cases, it is better that the code fires an event and allows you to control the code, or the code, which must have a dependency, to listen to the event and act accordingly.

For example, you might be creating a library that other people will use. They do not have source code or somehow cannot / cannot modify it (or should not). Your documentation indicates that certain events occur under certain circumstances. In turn, they can respond to these events.

Or maybe your company has some domain libraries. You control them and you can modify them, but in architecture they are usually considered working because they are currently encoded and should not be changed. (You do not want to conduct a QA round to re-check the updated code, the code belongs to another department, and they do not want you to change it, etc.). And you are in a position where you want the code to be able to do different things in different circumstances / environments. If this code occurs and when it is necessary, you can connect your code to it (and / or swap accordingly) without having to contact this code.

Just a few examples, I'm sure others have more.

+10
source

My question is: why create an event listener when calling a function, will it work fine?

What if you don’t know which function you want to call?

Take a classic example - a button that a user can click. Whoever writes the library does not know what function you want to call when the button is pressed. It would also be quite difficult if each button could call only the same function when pressed.

So instead, you can attach an event handler to the event. Then, when the event is fired, Button can do what it needs, without having to know at compile time exactly what function it should call.

+4
source

In short, you can write code without an event listener, but with the event listener you can use the same code as the library.

+1
source

Even with the detailed answers above, I still had problems understanding what the real difference is between using a controller / function OR an event listener.

One of the things that was missing in all of these answers is that using events and event listeners is useful when you don't want to put together your code so closely . Each function, class, etc. Must have a single goal.

Suppose you received an API request from an outsider. In my case, my exact problem with understanding this concept was when I get API calls from Stripe Webhooks.

The goal of Stripe Webhooks: let's say a client spends $ 10,000 on your website. Your standard procedure is Authentication and Capture. Update your database to reflect their new membership status. In an ideal world, and in the case of our company, 999/1000 times, it goes perfectly. Either their card will be declined on the spot, or the payment will go through. In both cases, we send them a notification email.

But what about the time 1/1000 when the user pays, and Stripe returns a "Card Error" error (this can be many different things)? In our case, we send them an e-mail and inform them that billing has failed. The problem we are facing is that some BANKS investigate large payments that are returned as an Error, but then, after a few minutes, the bank authorizes the payments and the payment is fixed.

So what is there to do? Enter the strip of Webhooks. Stripe Webhooks will go to the API endpoint if something like this happens. In fact, Stripe Webhooks can use your API every time a payment is not processed instantly, verified, received, or if a customer requests a refund.

This is where the event receiver comes in handy. The bar fires through POST with client information, as well as the Webhook type. Now we will process this, update the database and send them a successful email.

But why not just use the standard route and controller? The reason why we do not just use the standard route and controller is because we need to either change already defined functions, classes, etc., Or create a new series of classes that are connected together, for example → Stripe API Calls Received Database update, Email sending. Instead of binding them together, we use an event receiver to first accept an API call, and then click on each of these classes, functions, etc., leaving everything unconnected.

I searched everywhere and I think the Laravel documentation explains this best. When I gave a concrete example, I finally realized what the purpose of the event listener is:

Events are a great way to separate the various aspects of your application, as a single event can have multiple listeners that are independent of each other. For example, you can send Slack notifications to your user every time an order is sent. Instead of associating an order processing code with a Slack notification code, you can trigger an OrderShipped event, which the listener can receive and convert to a Slack notification.

https://laravel.com/docs/5.6/events

+1
source

I think that the main reason for events compared to function calls is that events are “ tapped ” and calls are “ made ”. Thus, a function call is always made for another object, while listeners “ choose ” to listen to the event that will be broadcast from your object. The observer design is a good study for this possibility. Here is a brief example of node.js that illustrates the concept:

var events = require('events'); var Person = function(pname) { var name = pname; }; var james = new Person('james'); var mary = new Person('mary'); var loudmouth = new Person('blabberer'); loudmouth.mouth = new events.EventEmitter(); //jame observer. james.read_lips = function(msg){ console.log("james found out: " + msg); }; //james adds his event to the emitter event listener. james.enter_elevator = function(){ console.log('james is in the elevator'); //NOTE: james adds HIMSELF as a listener for the events that may //transpire while he is in the elevator. loudmouth.mouth.on('elevator gossip', james.read_lips) }; //james removes his event from the emitter when he leaves the elevator. james.leave_elevator = function(){ // read lips is how james responds to the event. loudmouth.mouth.removeListener('elevator gossip', james.read_lips); console.log('james has left the elevator'); }; //mary observer mary.overhear = function(msg){ console.log("mary heard: " + msg); }; //mary adds her observer event to the emitter event listeners mary.enter_elevator = function(){ // overhear is how mary responds to the event. console.log('mary is in the elevator'); //NOTE: now mary adds HERSELF to the listeners in the elevator and //she observes using a different method than james which suits her. loudmouth.mouth.on('elevator gossip', mary.overhear); }; loudmouth.speaks = function(what_is_said){ console.log('loudmouth: ' + what_is_said); this.mouth.emit('elevator gossip', what_is_said); }; james.enter_elevator(); mary.enter_elevator(); loudmouth.speaks('boss is having an affair'); james.leave_elevator(); loudmouth.speaks('just kidding'); console.log('james did not hear the last line because he was not listening anymore =)'); 

therefore, in this “story”, actors choose to listen or when not to listen to third-person events. Hope this helps.

0
source

All Articles