summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/subscription.js.es6
blob: 62d1604fe9eaabbe42747fa82eae1dea63f6ac48 (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
/* global Vue */

(() => {
  class Subscription {
    constructor(containerElm) {
      this.containerElm = containerElm;

      const subscribeButton = containerElm.querySelector('.js-subscribe-button');
      if (subscribeButton) {
        // remove class so we don't bind twice
        subscribeButton.classList.remove('js-subscribe-button');
        subscribeButton.addEventListener('click', this.toggleSubscription.bind(this));
      }
    }

    toggleSubscription(event) {
      const button = event.currentTarget;
      const buttonSpan = button.querySelector('span');
      if (!buttonSpan || button.classList.contains('disabled')) {
        return;
      }
      button.classList.add('disabled');

      const isSubscribed = buttonSpan.innerHTML.trim().toLowerCase() !== 'subscribe';
      const toggleActionUrl = this.containerElm.dataset.url;

      $.post(toggleActionUrl, () => {
        button.classList.remove('disabled');

        // hack to allow this to work with the issue boards Vue object
        if (document.querySelector('html').classList.contains('issue-boards-page')) {
          Vue.set(
            gl.issueBoards.BoardsStore.detail.issue,
            'subscribed',
            !gl.issueBoards.BoardsStore.detail.issue.subscribed,
          );
        } else {
          buttonSpan.innerHTML = isSubscribed ? 'Subscribe' : 'Unsubscribe';
        }
      });
    }

    static bindAll(selector) {
      [].forEach.call(document.querySelectorAll(selector), elm => new Subscription(elm));
    }
  }

  window.gl = window.gl || {};
  window.gl.Subscription = Subscription;
})();