Pagination
Starting with pagination which is easy. Tastypie already provides that information for you in the “meta” section of response:
1 2 3 4 5 6 7 8 |
"meta": { "limit": 20, "next": "/api/v1/[whatever]&offset=20&limit=20&format=json", "offset": 0, "previous": null, "total_count": 877 }, |
You just need to follow the next and previous links. Which I implemented in the fetchNext and fetchPrev methods. Also there is a fetchPage method to fetch a given page. The page links can be generated onRender based on the meta information.
In your view you can just have the following method and will work like a charm. (Example is using marionette but obviously this would work in plain backbone).
View
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 |
var PaginationView = Marionette.CollectionView.extend({ ... events: { 'click a.link.previous': 'previousPage', 'click a.link.next': 'nextPage', 'click a.link.page': 'goToPage' }, initialize: function () { this.collection.on('reset', this.render); }, render: function () { var pages = []; if (this.collection.length > 0) { var i, max_page = this.collection.meta.total_count / this.collection.meta.limit; var current = this.collection.meta.offset / this.collection.meta.limit; for (i = 0; i < max_page; i++) { pages.push({ current: (current === i), page: i + 1 }); } } this.$el.html(this.template({ pages: pages })); }, previousPage: function (ev) { ev.preventDefault(); this.collection.fetchPrevious(); return false; }, nextPage: function (ev) { ev.preventDefault(); this.collection.fetchNext(); return false; }, goToPage: function (ev) { ev.preventDefault(); this.collection.fetchPage($(ev.currentTarget).data('page')); return false; } }); |
Template
1 2 3 4 5 6 7 8 9 10 11 |
<ul class="pagination"> <li><a href="#" class="link previous"><span aria-hidden="true">«</span><span class="sr-only">Previous</span></a></li> {{#each pages }} <li class="{{#if this.current }}active{{/if}}"> <a href="#" class="link page" data-page="{{ @index }}"> {{ this.page }} </a> </li> {{/each}} <li><a href="#" class="link next"><span aria-hidden="true">»</span><span class="sr-only">Next</span></a></li> </ul> |
Recent comments