How to update item without using save button option

There are a few things that you’ll want to be aware of when setting up auto-save;

  1. Always include a <form> tag to deal with the “submit” action, or you might end up submitting something else in your app.
  2. Debounce your save action if you are saving on “key-down”, else you’ll kill browser performance and overload your server.
  3. Cancel debounces if you end up saving via another way, eg: submit
  4. Pressing [Enter] on a <input type="text"> field causes the <form>s “submit” event to fire

With that in mind, here is how I typically handle this (also using ember-data):

// app/controllers/foobar.js
import Ember from 'ember';

export default Ember.Controller.extend({

    saveModel: function(){
        var model = this.get('model');
        // Avoid un-needed `.save()`s if user clicks Submit w/o typing anything
        if (model.get('hasDirtyAttributes')) {
            model.save().then( function(){
                // handle success
            }, function( error ){
                // handle failure
            });
        }
    },

    actions: {

        modelChanged: function(){
            var debounced = Ember.run.debounce(this, this.saveModel, 2000); // 2 seconds
            this.set('debounced', debounced);
        },

        submitForm: function(){
            var debounced = this.get('debounced');
            if (debounced) {
                Ember.run.cancel( debounced );
            }
            this.saveModel();
        }

    } // :actions
});
<!-- app/templates/foobar.hbs -->
<form {{action "submitForm" on="submit"}}>
    {{input type="text" value=model.attributeName key-press="modelChanged"}}
    <button type="submit">Save</button>
</form>

I also “buffer changes” but that’s kind of a different topic. This is the basic logic behind my “auto-save” feature.

1 Like