BigW Consortium Gitlab

pager.js.es6 1.83 KB
Newer Older
1
(() => {
2 3 4
  const ENDLESS_SCROLL_BOTTOM_PX = 400;
  const ENDLESS_SCROLL_FIRE_DELAY_MS = 1000;

5
  const Pager = {
6 7
    init(limit = 0, preload = false, disable = false, callback = $.noop) {
      this.limit = limit;
8
      this.offset = this.limit;
9 10
      this.disable = disable;
      this.callback = callback;
Fatih Acet committed
11 12 13 14 15
      this.loading = $('.loading').first();
      if (preload) {
        this.offset = 0;
        this.getOld();
      }
16
      this.initLoadMore();
Fatih Acet committed
17
    },
18

19
    getOld() {
Fatih Acet committed
20
      this.loading.show();
21 22 23 24
      $.ajax({
        type: 'GET',
        url: $('.content_list').data('href') || window.location.href,
        data: `limit=${this.limit}&offset=${this.offset}`,
25
        dataType: 'json',
26
        error: () => this.loading.hide(),
27
        success: (data) => {
28 29 30 31
          this.append(data.count, data.html);
          this.callback();

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

41 42
    append(count, html) {
      $('.content_list').append(html);
Fatih Acet committed
43
      if (count > 0) {
44
        this.offset += count;
Fatih Acet committed
45
      } else {
46
        this.disable = true;
Fatih Acet committed
47 48
      }
    },
49

50
    isScrollable() {
51 52
      const $w = $(window);
      return $(document).height() > $w.height() + $w.scrollTop() + ENDLESS_SCROLL_BOTTOM_PX;
53 54
    },

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

72 73
  window.Pager = Pager;
})();