I’ve been reading O’Reilly’s JavaScript: The Definitive Guide (6th ed), and have been examining the very first example program — a loan calculator. However, the structure of this just bugs me — I know that it’s a book example, and hence probably not the best way of going about things for the sake of simplicity, so I’m curious as to how a professional using best practices would structure the same thing.
For example, the main function, calculate(), which is called onChange to any of the input fields, contains within it a TON of stuff that doesn’t have anything to do with calculating anything — display code, for instance — how would you pull that out to separate concerns?
It’d make me feel better if you could modularize the individual tasks that are to be done and put the major control into the function something like this:
run() {
getdata();
calculate();
if (isFinite(monthly)) {
display();
save(arg1, arg2, arg3, arg4); }
else {
cleardisplay(); }
But I have no idea what I’m talking about. Is there some way to do it with the Object Literal pattern? I guess I’m just asking how you would do it idiomatically.
This is a very contrived example, but you can see some concepts here on how to separate “business logic” from both the input data and the display output. I’ve used jQuery here just for the
$,.val(), and.click()helper functions, you could use any other library, or none at all.HTML:
Javascript:
Live Demo: http://jsfiddle.net/Wd49U/
Some notes:
The input is handled by passing in callback functions which return the value to be used, this callback style offers extreme flexibility in where and how you want to get your data into the calculator.
I assign the “click” handler outside of the calculator function because that method of triggering it, isn’t really the calculators responsibility, maybe in another case you would want to call
run()on a timer, or from another event.Most importantly, it really depends on your specific use case for what the best way might be. I hope this helps you get some ideas.