I'm working on (and have actually finished) a project that fetches price quotes based on user-entered data. I've written the code already and it works fine. It's written in javascript/jQuery using events and functions, more like this (example I just wrote for this question, not actual code):
// event - when the quantity field changes
$('input[name=quantity]').change(function(){
// get the product
var product = $('input[name=product]').val();
// run function to set the base price
setBasePrice(this.value,product);
});
// function - set the base price
function setBasePrice(quantity,product){
var basePrice = quantity * getTierPrice(quantity,product);
// show the base price to user
$('.basePrice').empty().val(basePrice);
};
// function - set price based on quantity and product
function getTierPrice(quantity,product){
// switches through 6 tiers (based on quantity)
// e.g. - If product is x and quantity is y, price = z
// returns a value
};
There are many more working parts but I wrote that to illustrate how it's put together. It just seems really verbose and a lot of moving parts. When it comes time to update it, it's a pain.
But I'm wondering if I should be using OOP for something like this? I really just want to get to the root of javascript best practice and find out how something like this should really be put together. I feel like a lot of the code I write, although works, isn't always the best way, maybe it's because I am self taught and haven't really dug in deep enough.
I broke the functionality into pieces if it helps to understand what is going on. It's not crucial for you to understand how every bit works:
Things I'm expecting
= zip code (number)
= product (string)
= quantity (number)
- Need to verify number is between x and y (e.g. - 100 to 10000)
= artwork colors (number)
- Need to verify number is between x and y (e.g. - 0 to 6)
Things I'm calculating
= base price (number)
- Depends on the product selected
- Depends on the quantity entered (6 tiers of pricing based on quantity)
e.g. - "Product 1" quantity of 101 to 200 = $9, quantity of 201 to 300 = $7, etc
= screen charge (number)
- Depends on the number of artwork colors entered
- Depends on the quantity entered (uses same tier as when calculating base price)
e.g. - "Product 1" quantity of 101 to 200 add 1.00 per artwork color
- Gets rolled into the base price
e.g. - base price = base price + (artwork colors*quantity);
= shipping cost (hits url via ajax to fetch rate, returns number)
- Depends on zip code entered
- Depends on product selected (each product has different weight)
Things I need to output
= final price
= shipping cost
= base price
So should I be using OOP, should I look at the YUI Module Pattern? If so, at a high level, how would I start? I don't need a full code sample, just an idea of where to begin. I really want my code to look good and be structured properly. Any advice, resource links, etc is greatly appreciated.