aboutsummaryrefslogtreecommitdiff
path: root/javascript/app/components/infinite-list.js
blob: 02e1943a752161c169e668a619bbd8eebf99e284 (plain) (blame)
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
import Component from '@ember/component';
import { run } from '@ember/runloop';
import { observer } from '@ember/object';

let pageNumber;
let updating = false;

function initialize(component) {
  component.set('renderedElements',component.get('elements').slice(0,component.get('perPage')));
  pageNumber = 1;
}

export default Component.extend({
  renderedElements : [],
  init() {
    this._super(...arguments);
    initialize(this);
  },
  elementsObserver : observer('elements',function() {
    initialize(this);
    const containerElement = document.getElementById(this.get('containerElementId'));
    if(containerElement) {
      containerElement.scrollTop = 0;
    }
  }),
  didInsertElement() {
    const containerElement = document.getElementById(this.get('containerElementId'));
    if(containerElement) {
      const component = this;
      containerElement.onscroll = function() {
        const perPage = component.get('perPage');
        const elements = component.get('elements');

        if(!updating &&
           (pageNumber * perPage < elements.length) &&
           (containerElement.scrollTop + containerElement.offsetHeight
            > component.element.offsetHeight - 100)) {

          updating = true;
          run.next(component,() => {
            const newElements = elements.slice(pageNumber * perPage,(pageNumber + 1) * perPage);
            component.get('renderedElements').pushObjects(newElements);
            pageNumber ++;
            updating = false;
          });
        }
      }
    }
  }
});