1
У меня есть два метода в coffescript, они выглядят так:Сделать Coffescript код DRY
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()
Как и все увидеть там много повторений этот код выглядит с этим очень некрасиво. Как я могу сделать этот код более сухим?
Два обработчики событий вы связаны по всей видимости, будут полностью идентичны. Итак, почему бы не определить его как функцию и передать функцию как обработчик для каждого события? – arghbleargh
Не могли бы вы объяснить это более подробно или, может быть, показать мне простой пример? –