Custom event or call a function. What is the difference?

Hoi guys,

I wonder what is the difference between creating a custom event and applying .trigger(‘customEvent’) and just calling a function.

Situation 1.
$(‘button’).on(‘click’, function(e){
$(this).trigger(‘saveIt’);
});

Situation 2.
$(‘button’).on(‘click’, function(e){
$(this).saveIt();
});

It seems to me both should be doing the same action. Is so, why create custom events?

Thank you for your replay.

Julia

1 Like

Hey @MrsColombo, have a look at these couple links.Hope it clear things up for you. :slight_smile:

Introducing Custom Events

http://stackoverflow.com/questions/11204086/what-is-better-in-javascript-custom-events-or-normal-function-calls

1 Like

@Azdrian’s link has a couple nice answers on this.
As a rule of thumb, I’d only use events in two cases:

  1. If the action you want to trigger (the function) could be called by more than one source and you don’t yet know which ones.
  2. If, conversely, your action may do different things depending on many different types of event that could trigger it.

In all cases you could go completely without events and call functions directly. But the more complex your system gets (e.g. many different buttons on lots of pages that could trigger your function), the more convenient do events become.