Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is better in JavaScript Custom Events or normal Function calls? [closed]

In Js code if there are two js objects(One Handling a UI(example a Form) and other posting a request to a server.

What would be the better way to interact between these components using Custom Events or Normal Function call.

For Example.

  clickForm = function(){
      validateForm();
      $(document).trigger("submitForm",{"userData":userData});//Event submitForm listened by formManager submitForm method.
  }

OR

clickForm = function(){
     validateForm();
     formManager.submitForm(userData);
  }

clickForm method is part of the UI Component which is responsible for managing the UI interaction of the HTML Code.This function is usually called when a submit button is clicked.

submitForm method is part of the core Object whose responsibility is to make request to the server,parse the response and then send the result to the UI Component.

Which one of these two methods is a better way to interact. Any Suggestions?

like image 946
Aditya Bhatia Avatar asked Jun 26 '12 09:06

Aditya Bhatia


1 Answers

"Better" is a tricky concept. :-)

Using events couples the objects more loosely, which is usually considered a good thing, and allows for the possibility going forward of more than just the two objects collaborating (for instance, more than one subscriber to the event; and conversely an object could subscribe to the event on two sources).

The event mechanism will have more overhead, which doesn't matter in most cases (certainly not when submitting a form), but could in a small class of cases (something that happens thousands of times a second). Event mechanisms can be a bit trickier to read and debug, as well.

like image 64
T.J. Crowder Avatar answered Sep 21 '22 12:09

T.J. Crowder