我正在使用 KnockoutJS 和 Twitter Bootstrap 构建一个简单的分页表视图。现在,除了在页面加载时我无法加载初始数据集之外,我一切正常。查看我的视图模型,您可以看到在通过 RESTful API“导航”通过客户存储库时加载了正确的数据。
如何获取要加载的初始数据?
<script>
var ListViewModel = function() {
var self = this;
window.viewModel = self;
//Properties
self.list = ko.observableArray();
self.pageSize = ko.observable(20);
self.pageIndex = ko.observable(0);
self.itemCount = ko.observable();
self.maxPageIndex = ko.dependentObservable(function () {
return Math.ceil(self.itemCount() / self.pageSize()) - 1;
});
self.allPages = ko.dependentObservable(function () {
var pages = [];
for (i = 0; i <= self.maxPageIndex() ; i++) {
pages.push({
pageNumber: (i + 1)
});
}
return pages;
});
//navigation Functions
self.previousPage = function () {
if (self.pageIndex() > 0) {
self.pageIndex(self.pageIndex() - 1);
}
self.getItems();
};
self.nextPage = function () {
if (self.pageIndex() < self.maxPageIndex()) {
self.pageIndex(self.pageIndex() + 1);
}
self.getItems();
};
self.moveToPage = function (index) {
self.pageIndex(index);
self.getItems();
};
//API interactions
self.getItems = function () {
$.ajax({
url: '/api/customer/?pageNumber='+self.pageIndex()+"&pageSize="+self.pageSize(),
async: false,
dataType: 'json',
success: function (result) {
self.list(result);
}
});
};
self.getTotalItemCount = function() {
//TODO: Add call to fetch total number of customers in the database and set it to self.itemCount property.
};
};
$(document).ready(function() {
ko.applyBindings(new ListViewModel());
});
</script>