Hypothetical example - you have an "Items" collection, where each item has a quantity and price that's stored in the db.
That quantity is an input field.
We want the database to be updated when the quantity is changed - with no "submit" button. There are multiple ways of going about this. Two examples:
Update db on "changed":
'change input.qty': function (evt) {
var qty = $(evt.target).val();
if (qty==null){
qty=0;
};
Items.update(this._id,{$set:{quantity: Number(qty)}});
},
Update db on "keyup":
'keyup input.qty': function (evt) {
var qty = $(evt.target).val();
if (qty==null){
qty=0;
};
Items.update(this._id,{$set:{quantity: Number(qty)}});
},
1 is more efficient - it only performs the update call once, after the user has clicked outside of the input box. However, it's a worse user experience, because the updates are not reflected on the page as they're typing. (For example, say the "price" field is calculated reactively based on your input quantity)
2 is a better user experience but can be extremely inefficient(ie typing in 103.58 makes FIVE database calls)
Are there better alternatives or a good middle ground?
That's the exact situation for which _.throttle
method was created.
'keyup input.qty': _.throttle(function (evt) {
...
}, 350),
When you wrap your handler with _.throttle
that way, it will be called only once per the given number of milliseconds, even if the input keep changing more frequently.
350
is a good value in most cases, though the exact optimum value may depend on the interface you're designing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With