Business and User Interface Logic
Terminology
- Business logic: The code responsible for handling the evaluation and manipulation of data; does not require any user interface.
- User interface logic: The code responsible for the interaction between the user and the application; handles tasks such as event listening, user input forms, DOM manipulation, display and styling. We have not covered how to write the actual code for this yet; don't worry!
Summary
Because they are responsible for entirely separate things, code for business logic and user interface logic should always be separated. We have not yet written any applications that use both; but as we explore jQuery in the upcoming lessons, always keep this rule in mind.
Example
The following code prompts the user for two numbers, uses the included add()
function to add these two numbers together, and provides the sum to the user in an alert box:
function add(number1, number2) {
return number1 + number2;
}
const number1 = parseInt(prompt("Enter a number:"));
const number2 = parseInt(prompt("Enter another number:"));
alert(add(number1, number2));
Terminology
-
Event handler: an event handler "listens" to the element(s) to which it's attached and responds when a certain event is triggered.
.click()
is a click listener, which is a type of event handler that responds when an element to which it's attached is clicked. - Callback: a function passed as an argument to another function. A callback function is not executed immediately; One use of callback functions is that they are passed into event handlers to be executed at a future time.
Resources
- Download jQuery here. - Make sure to get the most recent uncompressed development version.
Examples
Link jQuery before your scripts that use it:
<head>
<script src="js/jquery-3.5.1.js"></script>
<script src="js/scripts.js"></script>
</head>
Select a tag and bind an event handler to it:
$("h1").click(function() {
alert("This is a header.");
});
The part function() { alert("This is a header."); }
is considered the callback because it is being passed as an argument into the method .click()
.
Wrap all your jQuery code in callback passed to $(document).ready()
so that it is run after the page loads:
$(document).ready(function() {
$("h1").click(function() {
alert("This is a header.");
});
});
To check if an event handler is attached properly, right-click the element you want to check, Inspect, and click Event Listeners.
Latest comments (5)
You can avoid to use ready if you bind your handlers directly to document and use event.target to check if it suffices:
To do that, you even don't need jQuery.
Awesome thanks! I bet that is something that is an upcoming lesson as well. :)
Yes
Hey,
I graduated from epicodus aroind 2015. Glad to see a fellow student here!
I am really enjoying it so far!