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?
"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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With