BigW Consortium Gitlab

task_list.js 1.39 KB
Newer Older
1
import 'deckar01-task_list';
2
import axios from './lib/utils/axios_utils';
3
import Flash from './flash';
4

5
export default class TaskList {
6 7 8
  constructor(options = {}) {
    this.selector = options.selector;
    this.dataType = options.dataType;
9
    this.fieldName = options.fieldName;
Simon Knox committed
10
    this.onSuccess = options.onSuccess || (() => {});
11
    this.onError = function showFlash(e) {
12 13
      let errorMessages = '';

14 15
      if (e.response.data && typeof e.response.data === 'object') {
        errorMessages = e.response.data.errors.join(' ');
16 17 18 19 20
      }

      return new Flash(errorMessages || 'Update failed', 'alert');
    };

21 22 23 24
    this.init();
  }

  init() {
25 26
    // Prevent duplicate event bindings
    this.disable();
Simon Knox committed
27
    $(`${this.selector} .js-task-list-container`).taskList('enable');
28
    $(document).on('tasklist:changed', `${this.selector} .js-task-list-container`, this.update.bind(this));
29 30 31
  }

  disable() {
Simon Knox committed
32
    $(`${this.selector} .js-task-list-container`).taskList('disable');
Simon Knox committed
33
    $(document).off('tasklist:changed', `${this.selector} .js-task-list-container`);
34 35 36
  }

  update(e) {
37
    const $target = $(e.target);
Simon Knox committed
38
    const patchData = {};
39
    patchData[this.dataType] = {
40
      [this.fieldName]: $target.val(),
41
    };
42 43 44

    return axios.patch($target.data('update-url') || $('form.js-issuable-update').attr('action'), patchData)
      .then(({ data }) => this.onSuccess(data))
45
      .catch(err => this.onError(err));
46 47
  }
}