我在coffescript中有两种方法,它们看起来像这样:
amount_calculation_when_unit_price_change = (parent) ->
$(".unit_price input").bind "keyup change", (e) ->
unit_price = @value.replace(/\,/g,'.')
quantity = $(this).closest(parent).find(".quantity input").val().replace(/\,/g,'.')
discount = $(this).closest(parent).find(".discount input").val().replace(/\,/g,'.') if $('.discount input').length > 1
if discount == ""
discount = 0
discount_type = $(this).closest(parent).find(".discount_type select").val() if $('.discount_type select').length > 1
value = ((parseFloat(unit_price) * parseFloat(quantity)))
if discount_type == "Absolute"
value = value - parseFloat(discount).toFixed(2)
else if discount_type == "Relative"
discount_price = value * parseFloat(discount/100).toFixed(2)
value = value - discount_price
amount = $(this).closest(parent).find(".amount")
if value.toString().match(pricePattern)
amount.html('<br/>' + '$' + "#{(value.toFixed(2))}")
else
amount.html('<br/>' + '$' + "0.00")
calculate_total()
amount_calculation_when_quantity_change = (parent) ->
$(".quantity input").bind "keyup change", (e) ->
quantity = @value.replace(/\,/g,'.')
unit_price = $(this).closest(parent).find(".unit_price input").val().replace(/\,/g,'.')
discount = $(this).closest(parent).find(".discount input").val().replace(/\,/g,'.') if $('.discount input').length > 1
if discount == ""
discount = 0
discount_type = $(this).closest(parent).find(".discount_type select").val() if $('.discount select').length > 1
value = ((parseFloat(unit_price) * parseFloat(quantity)))
if discount_type == "Absolute"
value = value - parseFloat(discount).toFixed(2)
else if discount_type == "Relative"
discount_price = value * parseFloat(discount/100).toFixed(2)
value = value - discount_price
amount = $(this).closest(parent).find(".amount")
if value.toString().match(pricePattern)
amount.html('<br/>' + '$' + "#{(value.toFixed(2))}")
else
amount.html('<br/>' + '$' + "0.00")
calculate_total()
就像所有人都看到有很多重复一样,这段代码看起来非常难看。 如何让这段代码变得更干?
答案 0 :(得分:0)
尝试这样的事情:
amount_calculation_when_unit_price_change = (parent) ->
for class in ["unit_price, quantity"]
values = {}
$(".#{class} input").bind "keyup change", (e) ->
values[class] = @value.replace(/\,/g,'.')
...