BigW Consortium Gitlab

task_list.js 1.35 KB
Newer Older
1
import 'deckar01-task_list';
2
import Flash from './flash';
3

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

      if (response.responseJSON) {
        errorMessages = response.responseJSON.errors.join(' ');
      }

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

20 21 22 23
    this.init();
  }

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

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

  update(e) {
36
    const $target = $(e.target);
Simon Knox committed
37
    const patchData = {};
38
    patchData[this.dataType] = {
39
      [this.fieldName]: $target.val(),
40 41 42
    };
    return $.ajax({
      type: 'PATCH',
43
      url: $target.data('update-url') || $('form.js-issuable-update').attr('action'),
44
      data: patchData,
45
      success: this.onSuccess,
46
      error: this.onError,
47 48 49
    });
  }
}