summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/droplab/plugins/input_setter.js
blob: b1716c7281018de871f10c6927b6dd1e045b3c15 (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
49
50
51
/* eslint-disable */

const InputSetter = {
  init(hook) {
    this.hook = hook;
    this.destroyed = false;
    this.config = hook.config.InputSetter || (this.hook.config.InputSetter = {});

    this.eventWrapper = {};

    this.addEvents();
  },

  addEvents() {
    this.eventWrapper.setInputs = this.setInputs.bind(this);
    this.hook.list.list.addEventListener('click.dl', this.eventWrapper.setInputs);
  },

  removeEvents() {
    this.hook.list.list.removeEventListener('click.dl', this.eventWrapper.setInputs);
  },

  setInputs(e) {
    if (this.destroyed) return;

    const selectedItem = e.detail.selected;

    if (!Array.isArray(this.config)) this.config = [this.config];

    this.config.forEach(config => this.setInput(config, selectedItem));
  },

  setInput(config, selectedItem) {
    const input = config.input || this.hook.trigger;
    const newValue = selectedItem.getAttribute(config.valueAttribute);

    if (input.tagName === 'INPUT') {
      input.value = newValue;
    } else {
      input.textContent = newValue;
    }
  },

  destroy() {
    this.destroyed = true;

    this.removeEvents();
  },
};

export default InputSetter;