The project needs to dynamically list the reviewers according to the amount. When the amount changes, the asynchronous request is executed. The problem now is that whether I change the amount or the quantity, the amount will be calculated and the asynchronous request will be executed,
Change of unit price or quantity each time ( Calculate the total amount ) Will execute asynchronous request, it consumes resources
What's a good optimization plan?
This is the JS code:
<script>
// 监听单价和数量的变化
$(document).on('input propertychange', '.cg-items-table tbody input.listen', function (e) {
var tr = $(this).parent().parent(),
unitPrice = parseFloat(tr.find('td:nth-child(5) input').val()),
quantity = parseFloat(tr.find('td:nth-child(6) input').val()),
amount = ((unitPrice ? unitPrice : 0) * (quantity ? quantity : 1));
tr.find('td:nth-child(8) input').val(amount.toFixed(2));
amountCalculation();
});
// 计算合计金额并执行异步请求
function amountCalculation() {
var totalAmount = 0;
// 填充行合计
$('.cg-items-table tbody tr').each(function (index) {
totalAmount += parseFloat($(this).find('.amount').val());
});
// 总金额赋值
$('.cg-items-table tfoot tr td:last-child input').val(totalAmount.toFixed(2));
getReviewers({
totalAmount: totalAmount
});
}
</script>
If the total price is not changed, there is no need for asynchronous request. 2. If the total price is changed, the previous request is meaningless and cancelled directly. 3. Avoid changing too fast and keep sending, make a delay
When the input is modified, the request is changed from listening to input property change to listening to blur