Skip to content

Instantly share code, notes, and snippets.

@amk221
Last active December 20, 2023 09:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amk221/d5e85ab4126c60e63373fdadf1d01ed6 to your computer and use it in GitHub Desktop.
Save amk221/d5e85ab4126c60e63373fdadf1d01ed6 to your computer and use it in GitHub Desktop.
Pagination
import { action } from '@ember/object';
export default function withPagination(Controller) {
return class extends Controller {
@action
previousPage() {
this.page--;
}
@action
nextPage() {
this.page++;
}
};
}
@withPagination
export default class extends Controller {
@tracked items = [];
@tracked page = 1;
// If you need pagination on a page, just stick this getter on it
get pagination() {
return pagination({
page: this.page,
perPage: 10,
items: this.items
});
}
}
<ButtonGroup class="pagination">
<Button
class="pagination__prev"
disabled={{@pagination.isFirstPage}}
aria-label={{t "previous"}}
{{on "click" @onPreviousPage}}
>
<Svg::Prev />
</Button>
<Button
class="pagination__next"
disabled={{@pagination.isLastPage}}
aria-label={{t "next"}}
{{on "click" @onNextPage}}
>
<Svg::Next />
</Button>
</ButtonGroup>
Showing {{this.startCount}} to {{this.endCount}} of {{this.totalCount}}
<Pagination @paginaton={{this.paginaton}}
export function pagination(data) {
return new PaginationViewModel(data);
}
export default class PaginationViewModel {
constructor({ page, perPage, items }) {
this.page = page;
this.perPage = perPage;
this.items = items ?? [];
}
get hasMore() {
return this.items.meta.paginationHasMore === 'true';
}
get startCount() {
return (this.page - 1) * this.perPage + 1;
}
get endCount() {
return this.startCount + this.items.length - 1;
}
get isFirstPage() {
return this.page === 1;
}
get isLastPage() {
return !this.hasMore;
}
get totalCount() {
return 'totalCount' in this.items.meta ? this.items.meta.totalCount : null;
}
get isSinglePage() {
return this.isFirstPage && this.isLastPage;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment