aboutsummaryrefslogtreecommitdiff
path: root/javascript/app/components/paginated-list.js
blob: 9d8561067064d48eb6a638df9768eff86cfa2322 (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
import Ember from 'ember';
function loadItems(store,component,url) {
  store.loadFromUrlPaginated(url).then((result) => {
    Ember.run.next(() => {
      component.set('total',result.total);
      component.set('items',result.items);
      component.set('first',result.linkHeader.first);
      component.set('next',result.linkHeader.next);
      component.set('prev',result.linkHeader.prev);
      component.set('last',result.linkHeader.last);
      
      const pageMatch = url.match(/(&|\?)page=(\d+)/);
      const perPageMatch = url.match(/(&|\?)per_page=(\d+)/);
      
      const page = pageMatch ? pageMatch[2] : 1;
      const perPage = perPageMatch ? perPageMatch[2] : 20;

      if(result.linkHeader.next || result.linkHeader.prev) {
        component.set('firstItemOnPage',(page - 1) * perPage + 1);
        if(!result.linkHeader.last) {
          component.set('lastItemOnPage',result.total);
        } else {
          component.set('lastItemOnPage',page * perPage);
        }
      }
    });
  });
}

export default Ember.Component.extend({
  store : Ember.inject.service('store'),
  init() {
    this._super(...arguments);
    if(this.get('url')) {
      loadItems(this.get('store'),this,this.get('url'));
    }
  },
  urlObserver : Ember.observer('url',function () {
    loadItems(this.get('store'),this,this.get('url'));    
    this.element.querySelector(".paginated-list-content").scrollTop = 0;    
  }),
  actions : {
    update(url) {      
      this.element.querySelector(".paginated-list-content").scrollTop = 0;
      loadItems(this.get('store'),this,url);
    }
  }
});