BigW Consortium Gitlab

pager.js 2 KB
Newer Older
1 2
import '~/lib/utils/common_utils';
import '~/lib/utils/url_utility';
3

4
(() => {
5 6 7
  const ENDLESS_SCROLL_BOTTOM_PX = 400;
  const ENDLESS_SCROLL_FIRE_DELAY_MS = 1000;

8
  const Pager = {
9
    init(limit = 0, preload = false, disable = false, callback = $.noop) {
10
      this.url = $('.content_list').data('href') || gl.utils.removeParams(['limit', 'offset']);
11
      this.limit = limit;
12
      this.offset = parseInt(gl.utils.getParameterByName('offset'), 10) || this.limit;
13 14
      this.disable = disable;
      this.callback = callback;
Fatih Acet committed
15 16 17 18 19
      this.loading = $('.loading').first();
      if (preload) {
        this.offset = 0;
        this.getOld();
      }
20
      this.initLoadMore();
Fatih Acet committed
21
    },
22

23
    getOld() {
Fatih Acet committed
24
      this.loading.show();
25 26
      $.ajax({
        type: 'GET',
27
        url: this.url,
28
        data: `limit=${this.limit}&offset=${this.offset}`,
29
        dataType: 'json',
30
        error: () => this.loading.hide(),
31
        success: (data) => {
32 33 34 35
          this.append(data.count, data.html);
          this.callback();

          // keep loading until we've filled the viewport height
36
          if (!this.disable && !this.isScrollable()) {
37 38 39 40
            this.getOld();
          } else {
            this.loading.hide();
          }
Fatih Acet committed
41 42 43
        },
      });
    },
44

45 46
    append(count, html) {
      $('.content_list').append(html);
Fatih Acet committed
47
      if (count > 0) {
48
        this.offset += count;
Fatih Acet committed
49
      } else {
50
        this.disable = true;
Fatih Acet committed
51 52
      }
    },
53

54
    isScrollable() {
55 56
      const $w = $(window);
      return $(document).height() > $w.height() + $w.scrollTop() + ENDLESS_SCROLL_BOTTOM_PX;
57 58
    },

59
    initLoadMore() {
Fatih Acet committed
60
      $(document).unbind('scroll');
61
      $(document).endlessScroll({
62 63
        bottomPixels: ENDLESS_SCROLL_BOTTOM_PX,
        fireDelay: ENDLESS_SCROLL_FIRE_DELAY_MS,
Fatih Acet committed
64
        fireOnce: true,
65
        ceaseFire: () => this.disable === true,
66 67 68
        callback: () => {
          if (!this.loading.is(':visible')) {
            this.loading.show();
69
            this.getOld();
70
          }
Fatih Acet committed
71 72
        },
      });
73
    },
Fatih Acet committed
74 75
  };

76 77
  window.Pager = Pager;
})();