Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to perform Update call when input field value is changed in Meteor JS?

Tags:

meteor

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:

  1. 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)}});
    },
    
  2. 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?

like image 558
Ilmar Avatar asked Dec 25 '22 04:12

Ilmar


1 Answers

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.

like image 193
Hubert OG Avatar answered May 20 '23 13:05

Hubert OG