Skip to content

Instantly share code, notes, and snippets.

@Digiman
Created July 18, 2015 11:23
Show Gist options
  • Save Digiman/4bb106d85fc80fd709a5 to your computer and use it in GitHub Desktop.
Save Digiman/4bb106d85fc80fd709a5 to your computer and use it in GitHub Desktop.
Small TypeScript (JS) class to use for observable arrays that need to be devided on pages.
// Взято по примеру из источника: http://blog.greatrexpectations.com/2012/07/11/paging-lists-with-knockout/
export class PagedObservableArray {
options: any;
//public members
allData: KnockoutObservableArray<any>;
pageSize: KnockoutObservable<number>;
pageIndex: KnockoutObservable<number>;
page: KnockoutComputed<any>;
pageCount: KnockoutComputed<number>;
nextPage: any;
previousPage: any;
constructor() {
this.options = {};
this.allData = ko.observableArray([]);
this.pageSize = ko.observable(10);
this.pageIndex = ko.observable(0);
this.nextPage = null;
this.previousPage = null;
//the current page data
this.page = ko.computed(() => {
var pageSize = this.pageSize(),
pageIndex = this.pageIndex(),
startIndex = pageSize * pageIndex,
endIndex = pageSize * (pageIndex + 1);
return this.allData().slice(startIndex, endIndex);
}, this);
//the number of pages
this.pageCount = ko.computed(() => {
return Math.ceil(this.allData().length / this.pageSize()) || 1;
});
}
// инициализация объекта с данными для построения страничного представления
init = (options) => {
this.options = options || {};
if ($.isArray(options))
this.options = { data: options };
//the complete data collection
this.allData(options.data);
//the size of the pages to display
this.pageSize(options.pageSize || 10);
//the index of the current page
this.pageIndex(0);
//move to the next page
this.nextPage = () => {
if (this.pageIndex() < (this.pageCount() - 1))
this.pageIndex(this.pageIndex() + 1);
};
//move to the previous page
this.previousPage = () => {
if (this.pageIndex() > 0)
this.pageIndex(this.pageIndex() - 1);
};
//reset page index when page size changes
this.pageSize.subscribe(() => { this.pageIndex(0); });
this.allData.subscribe(() => { this.pageIndex(0); });
}
add = (item) => {
this.allData.push(item);
}
remove = (item) => {
this.allData.remove(item);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment