我正在使用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>
答案 0 :(得分:1)
更改开始代码
$(document).ready(function() {
var vm = new ListViewModel()
vm.getItems()
ko.applyBindings(vm)
});