summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--app/assets/javascripts/autosave.js11
-rw-r--r--spec/javascripts/autosave_spec.js27
2 files changed, 28 insertions, 10 deletions
diff --git a/app/assets/javascripts/autosave.js b/app/assets/javascripts/autosave.js
index e8c59fab609..eca84ce16ce 100644
--- a/app/assets/javascripts/autosave.js
+++ b/app/assets/javascripts/autosave.js
@@ -1,5 +1,6 @@
/* eslint-disable no-param-reassign, prefer-template, no-void, consistent-return */
+import _ from 'underscore';
import AccessorUtilities from './lib/utils/accessor';
export default class Autosave {
@@ -13,7 +14,13 @@ export default class Autosave {
this.key = 'autosave/' + key;
this.field.data('autosave', this);
this.restore();
- this.field.on('input', () => this.save());
+ this.field.on('input', this.debounceInputHandler());
+ }
+
+ debounceInputHandler() {
+ return _.debounce(() => {
+ this.save();
+ }, Autosave.DEBOUNCE_TIMER);
}
restore() {
@@ -57,4 +64,6 @@ export default class Autosave {
dispose() {
this.field.off('input');
}
+
+ static DEBOUNCE_TIMER = 300;
}
diff --git a/spec/javascripts/autosave_spec.js b/spec/javascripts/autosave_spec.js
index 38ae5b7e00c..404e1b53bf4 100644
--- a/spec/javascripts/autosave_spec.js
+++ b/spec/javascripts/autosave_spec.js
@@ -1,4 +1,5 @@
import $ from 'jquery';
+import _ from 'underscore';
import Autosave from '~/autosave';
import AccessorUtilities from '~/lib/utils/accessor';
@@ -10,12 +11,24 @@ describe('Autosave', () => {
describe('class constructor', () => {
beforeEach(() => {
spyOn(AccessorUtilities, 'isLocalStorageAccessSafe').and.returnValue(true);
+ spyOn(_, 'debounce');
+ spyOn(Autosave.prototype, 'save');
spyOn(Autosave.prototype, 'restore');
+ autosave = new Autosave(field, key);
});
- it('should set .isLocalStorageAvailable', () => {
- autosave = new Autosave(field, key);
+ it('should debounce the input handler', () => {
+ expect(_.debounce).toHaveBeenCalled();
+ expect(autosave.save).not.toHaveBeenCalled();
+
+ const [cb, timer] = _.debounce.calls.argsFor(0);
+ cb(); // execute debounced callback
+ expect(timer).toEqual(Autosave.DEBOUNCE_TIMER);
+ expect(autosave.save).toHaveBeenCalled();
+ });
+
+ it('should set .isLocalStorageAvailable', () => {
expect(AccessorUtilities.isLocalStorageAccessSafe).toHaveBeenCalled();
expect(autosave.isLocalStorageAvailable).toBe(true);
});
@@ -59,12 +72,10 @@ describe('Autosave', () => {
Autosave.prototype.restore.call(autosave);
- expect(
- field.trigger,
- ).toHaveBeenCalled();
+ expect(field.trigger).toHaveBeenCalled();
});
- it('triggers native event', (done) => {
+ it('triggers native event', done => {
autosave.field.get(0).addEventListener('change', () => {
done();
});
@@ -81,9 +92,7 @@ describe('Autosave', () => {
it('does not trigger event', () => {
spyOn(field, 'trigger').and.callThrough();
- expect(
- field.trigger,
- ).not.toHaveBeenCalled();
+ expect(field.trigger).not.toHaveBeenCalled();
});
});
});