Javascript 如何在Knockout js中提供分页

Javascript 如何在Knockout js中提供分页,javascript,jquery,html,json,knockout.js,Javascript,Jquery,Html,Json,Knockout.js,JSON数据(test.JSON) 淘汰赛JS数据 function ExampleViewModel() { var self = this; self.ExampleData = ko.observableArray([]); self.update = function() { $.ajax("test.json", { success: function(allData) { var mapp

JSON数据(test.JSON)

淘汰赛JS数据

function ExampleViewModel() {
    var self = this;
    self.ExampleData = ko.observableArray([]);
    self.update = function() {
        $.ajax("test.json", {
            success: function(allData) {
                var mappeddata = $.map(allData, function(item) {
                    return new DataItem(item)
                });
                self.ExampleData(mappeddata);
            }
        });
    }
}

function DataItem(data) {
    ko.observable(data.name);
    ko.observable(data.progress);
}
var exampleViewModel = new ExampleViewModel();
ko.applyBindings(exampleViewModel);
如何提供分页并仅显示前两个值?­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­


您可以从下面的
self.Data
循环

function ExampleViewModel() {
  var self = this;
  self.ExampleData = ko.observableArray([]);
  self.CurrentPage = ko.observable(1);
  self.DataPerPage = ko.observable(2); // You can change from here if you want to show the data other than 2 per page
  self.Data = ko.pureComputed(function(){
   var startIndex = self.CurrentPage() === 1? 0 : (self.CurrentPage() - 1) * self.DataPerPage();
   return self.ExampleData().slice(startIndex, startIndex + self.DataPerPage())
  });
  self.update = function() {
    $.ajax("test.json", {
      success: function(allData) {
        var mappeddata = $.map(allData, function(item) {
          return new DataItem(item)
        });
        self.ExampleData(mappeddata);
      }
    });
  }
}
简单的例子:

函数ViewModel(){
var self=这个;
self.ExampleData=ko.observatarray([1,2,3,4,5,6,7,8,9]);
self.CurrentPage=ko.observable(1);//存储用户的当前页面
self.DataPerPage=ko.observable(2);//确定每页要查看多少数据
self.Data=ko.pureComputed(函数(){
var startIndex=self.CurrentPage()==1?0:(self.CurrentPage()-1)*self.DataPerPage();
返回self.ExampleData().slice(startIndex,startIndex+self.DataPerPage())
});
self.Next=函数(){
var totalData=self.ExampleData().length;
var currentPage=self.currentPage();
//如果长度为0,则不允许下一步
//如果我们在最后一页,不允许下一页
如果(totalData>=1&¤tPage<(Math.ceil(totalData/2)))self.currentPage(currentPage+1);
};
self.Prev=函数(){
var currentPage=self.currentPage();
//如果我们在第一页,不允许上一页
如果(当前页>1)自身当前页(当前页-1);
};
}   
$(文档).ready(函数(){
var myViewModel=newviewmodel();
应用绑定(myViewModel);
});

下一个 上
事实上,我在网站上工作,它有很多表(其中大多数需要分页),所以实际上我需要一些可重用的组件来分页,以便在所有需要分页的情况下使用它
此外,我还需要比这个问题的公认答案中提供的更高级的功能

所以我开发了这个问题的我自己的组件,在这里

更多细节,请继续阅读

JavaScript

function PagingVM(options) {
    var self = this;

    self.PageSize = ko.observable(options.pageSize);
    self.CurrentPage = ko.observable(1);
    self.TotalCount = ko.observable(options.totalCount);

    self.PageCount = ko.pureComputed(function () {
        return Math.ceil(self.TotalCount() / self.PageSize());
    });

    self.SetCurrentPage = function (page) {
        if (page < self.FirstPage)
            page = self.FirstPage;

        if (page > self.LastPage())
            page = self.LastPage();

        self.CurrentPage(page);
    };

    self.FirstPage = 1;
    self.LastPage = ko.pureComputed(function () {
        return self.PageCount();
    });

    self.NextPage = ko.pureComputed(function () {
        var next = self.CurrentPage() + 1;
        if (next > self.LastPage())
            return null;
        return next;
    });

    self.PreviousPage = ko.pureComputed(function () {
        var previous = self.CurrentPage() - 1;
        if (previous < self.FirstPage)
            return null;
        return previous;
    });

    self.NeedPaging = ko.pureComputed(function () {
        return self.PageCount() > 1;
    });

    self.NextPageActive = ko.pureComputed(function () {
        return self.NextPage() != null;
    });

    self.PreviousPageActive = ko.pureComputed(function () {
        return self.PreviousPage() != null;
    });

    self.LastPageActive = ko.pureComputed(function () {
        return (self.LastPage() != self.CurrentPage());
    });

    self.FirstPageActive = ko.pureComputed(function () {
        return (self.FirstPage != self.CurrentPage());
    });

    // this should be odd number always
    var maxPageCount = 7;

    self.generateAllPages = function () {
        var pages = [];
        for (var i = self.FirstPage; i <= self.LastPage() ; i++)
            pages.push(i);

        return pages;
    };

    self.generateMaxPage = function () {
        var current = self.CurrentPage();
        var pageCount = self.PageCount();
        var first = self.FirstPage;

        var upperLimit = current + parseInt((maxPageCount - 1) / 2);
        var downLimit = current - parseInt((maxPageCount - 1) / 2);

        while (upperLimit > pageCount) {
            upperLimit--;
            if (downLimit > first)
                downLimit--;
        }

        while (downLimit < first) {
            downLimit++;
            if (upperLimit < pageCount)
                upperLimit++;
        }

        var pages = [];
        for (var i = downLimit; i <= upperLimit; i++) {
            pages.push(i);
        }
        return pages;
    };

    self.GetPages = ko.pureComputed(function () {
        self.CurrentPage();
        self.TotalCount();

        if (self.PageCount() <= maxPageCount) {
            return ko.observableArray(self.generateAllPages());
        } else {
            return ko.observableArray(self.generateMaxPage());
        }
    });

    self.Update = function (e) {
        self.TotalCount(e.TotalCount);
        self.PageSize(e.PageSize);
        self.SetCurrentPage(e.CurrentPage);
    };

    self.GoToPage = function (page) {
        if (page >= self.FirstPage && page <= self.LastPage())
            self.SetCurrentPage(page);
    }

    self.GoToFirst = function () {
        self.SetCurrentPage(self.FirstPage);
    };

    self.GoToPrevious = function () {
        var previous = self.PreviousPage();
        if (previous != null)
            self.SetCurrentPage(previous);
    };

    self.GoToNext = function () {
        var next = self.NextPage();
        if (next != null)
            self.SetCurrentPage(next);
    };

    self.GoToLast = function () {
        self.SetCurrentPage(self.LastPage());
    };
}
最后但并非最不重要的一点是,确保不要忘记根据您的特殊viewModel更改html组件中的绑定,或者像这样用
和binding将所有组件包装起来

<div data-bind="with: PagingComponent()">
    <!-- put the component here -->
</div>


干杯

它说的是未捕获的类型错误:ko.pureComputed不是function@Amitya尝试使用ko.computed然后我很抱歉,先生,它显示所有数据,而不是前两个数据我也开始从你的示例中学习一些东西,但它无助于meDid你复制并粘贴我创建的代码?您能把它放在JSFIDLE中并共享吗?您应该在“DataPerPage”上执行foreach,而不是在“ExampleData”上执行可能重复的操作
<ul data-bind="visible: NeedPaging" class="pagination pagination-sm">
    <li data-bind="css: { disabled: !FirstPageActive() }">
        <a data-bind="click: GoToFirst">First</a>
    </li>
    <li data-bind="css: { disabled: !PreviousPageActive() }">
        <a data-bind="click: GoToPrevious">Previous</a>
    </li>

    <!-- ko foreach: GetPages() -->
    <li data-bind="css: { active: $parent.CurrentPage() === $data }">
        <a data-bind="click: $parent.GoToPage, text: $data"></a>
    </li>
    <!-- /ko -->

    <li data-bind="css: { disabled: !NextPageActive() }">
        <a data-bind="click: GoToNext">Next</a>
    </li>
    <li data-bind="css: { disabled: !LastPageActive() }">
        <a data-bind="click: GoToLast">Last</a>
    </li>
</ul>
function MainVM() {
    var self = this;

    self.PagingComponent = ko.observable(new Paging({
        pageSize: 10,      // how many items you would show in one page
        totalCount: 100,   // how many ALL the items do you have.
    }));

    self.currentPageSubscription = self.PagingComponent().CurrentPage.subscribe(function (newPage) {
        // here is the code which will be executed when the user change the page.
        // you can handle this in the way you need.
        // for example, in my case, I am requesting the data from the server again by making an ajax request
        // and then updating the component

        var data = /*bring data from server , for example*/
        self.PagingComponent().Update({

            // we need to set this again, why? because we could apply some other search criteria in the bringing data from the server, 
            // so the total count of all the items could change, and this will affect the paging
            TotalCount: data.TotalCount,

            // in most cases we will not change the PageSize after we bring data from the server
            // but the component allow us to do that.
            PageSize: self.PagingComponent().PageSize(),

            // use this statement for now as it is, or you have to made some modifications on the 'Update' function.
            CurrentPage: self.PagingComponent().CurrentPage(),
        });
    });

    self.dispose = function () {
        // you need to dispose the manual created subscription, you have created before.
        self.currentPageSubscription.dispose();
    }
}
<div data-bind="with: PagingComponent()">
    <!-- put the component here -->
</div>