summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/notifications_form.js
blob: 8b90da71bef0a7d53f6e88c44a2f53ac225315c7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import $ from 'jquery';
import { deprecatedCreateFlash as flash } from './flash';
import axios from './lib/utils/axios_utils';
import { __ } from './locale';

export default class NotificationsForm {
  constructor() {
    this.toggleCheckbox = this.toggleCheckbox.bind(this);
    this.initEventListeners();
  }

  initEventListeners() {
    $(document).on('change', '.js-custom-notification-event', this.toggleCheckbox);
  }

  toggleCheckbox(e) {
    const $checkbox = $(e.currentTarget);
    const $parent = $checkbox.closest('.form-check');

    this.saveEvent($checkbox, $parent);
  }

  // eslint-disable-next-line class-methods-use-this
  showCheckboxLoadingSpinner($parent) {
    $parent.find('.is-loading').removeClass('gl-display-none');
    $parent.find('.is-done').addClass('gl-display-none');
  }

  saveEvent($checkbox, $parent) {
    const form = $parent.parents('form').first();

    this.showCheckboxLoadingSpinner($parent);

    axios[form.attr('method')](form.attr('action'), form.serialize())
      .then(({ data }) => {
        $checkbox.enable();
        if (data.saved) {
          $parent.find('.is-loading').addClass('gl-display-none');
          $parent.find('.is-done').removeClass('gl-display-none');

          setTimeout(() => {
            $parent.find('.is-done').addClass('gl-display-none');
          }, 2000);
        }
      })
      .catch(() => flash(__('There was an error saving your notification settings.')));
  }
}