Skip to content

Autosaving using ember concurrency

Ștefan Rotariu edited this page Jul 14, 2017 · 1 revision

Most of the time you want a regular form with a submit button, but sometimes you may want to use the autosave UX pattern. You can easily achieve this in ember-do-forms by overriding the update function on the form itself.

In your controller or component, add the autosave function:

import Ember from 'ember';
import { task, timeout } from 'ember-concurrency';

const {
  Component,
  get,
  set
} = Ember;

export default Component.extend({
  // Optionally set a debounce interval
  debounce: 2000,

  saveModel: task(function* (object) {
    yield object.save();
  }).keepLatest(),

  autoSaveTask: task(function* (object, propertyName, value) {
    set(object, propertyName, value);
    yield timeout(get(this, 'debounce'));
    get(this, 'saveModel').perform(object);
  }).restartable()
});

And in your template, just use the auto save task:

{{#do-form model update=(action (perform autoSaveTask)) as |form|}}
  {{#form.do-field 'fullName' as |field|}}
    {{field.do-label 'Full name'}}
    {{field.do-control}}
  {{/form.do-field}}

  {{#form.do-field 'lastNamePublic' as |field|}}
    {{field.do-label 'Last name public'}}
    {{field.do-control 'checkbox' checked=model.lastNamePublic}}
    {{field.do-hint 'Should your last name be public?'}}
  {{/form.do-field}}
{{/do-form}}

Implementation idea from this blog post.

Clone this wiki locally