使用knockout js

时间:2018-05-03 08:47:41

标签: javascript jquery sorting knockout.js knockout-2.0

我正在使用分页和搜索过滤器创建表格。我们将表数据与搜索过滤器绑定,是否可以使用分页在表中创建搜索过滤器。如何在表格中创建分页,还执行搜索过滤器以及排序。

 function PlayersViewModel() {

    var self = this,x, i, suits;

    /* text field should be empty */
    self.filterText = ko.observable(""); // Text from search field

    //#region Constant Properties
    self.descending = "fa fa-arrow-down";
    self.ascending = "fa fa-arrow-up";
    //#endregion

    self.CurrentPage = ko.observable(1); // Store the current page of the user
    self.DataPerPage = ko.observable(5); // To identify how many data we want to see per page

    //#region Knockout Observables
    // Observable array that represents each column in the table
    self.columns = ko.observableArray([
        { property: "id", header: "ID", type: "number", state: ko.observable("") },
        { property: "name", header: "Name", type: "string", state: ko.observable("") },
        { property: "time", header: "Time", type: "date", state: ko.observable("") },
        { property: "dob", header: "Date of Birth", type: "date", state: ko.observable("") },
        { property: "address", header: "Address", type: "string", state: ko.observable("") },
        { property: "msg", header: "Body", type: "string", state: ko.observable("") }
    ]);

    // Observable array that will be our data
    self.players = ko.observableArray([
       { id: "01", name: "Micky", time: "2015-02-09 4:46:56.678", dob: "10/20/1974", address: "London", msg: "Received Message" },
       { id: "02", name: "Griffey", time: "2015-03-09 4:46:54.678", dob: "11/21/1969", address: "Russia", msg: "Received Message" },
       { id: "03", name: "Derek", time: "2015-01-07 4:46:55.678", dob: "6/26/1931", address: "London", msg: "Send Message" },
       { id: "04", name: "Steven", time: "2015-03-09 4:46:56.678", dob: "2/10/1963", address: "Russia", msg: "Send Message" },
       { id: "05", name: "Jafer", time: "2015-02-09 5:46:56.540", dob: "12/18/1886", address: "London", msg: "Received Message" },
       { id: "06", name: "Jenifer", time: "2015-01-14 4:52:16.379", dob: "11/29/1970", address: "China", msg: "Send Message" },
       { id: "07", name: "Jones", time: "2015-03-08 5:26:33.600", dob: "8/24/1895", address: "London", msg: "Received Message" },
       { id: "08", name: "Micky", time: "2015-02-09 4:46:56.678", dob: "10/20/1974", address: "London", msg: "Received Message" },
       { id: "09", name: "Bruce", time: "2015-03-09 4:46:54.678", dob: "11/21/1969", address: "Russia", msg: "Received Message" },
       { id: "10", name: "Peter", time: "2015-01-07 4:46:55.678", dob: "6/26/1931", address: "London", msg: "Send Message" },
       { id: "11", name: "Wayne", time: "2015-03-09 4:46:56.678", dob: "2/10/1963", address: "Russia", msg: "Send Message" },
       { id: "12", name: "Sam", time: "2015-02-09 5:46:56.540", dob: "12/18/1886", address: "London", msg: "Received Message" },
       { id: "13", name: "Jenifer", time: "2015-01-14 4:52:16.379", dob: "11/29/1970", address: "China", msg: "Send Message" },
       { id: "14", name: "Smith", time: "2015-03-08 5:26:33.600", dob: "8/24/1895", address: "London", msg: "Received Message" }
    ]);
    //#endregion

    /* script for search filter */

    suits = self.players();


    for ( i = 0; i < suits.length; i++) {
        suits[i]["search_content"] = ">";
        for ( x in suits[i] ) {
            if ( !suits[i].hasOwnProperty(x) || x == "search_content" || typeof suits[i][x] !== "string") {continue;}
            suits[i]["search_content"] += suits[i][x].toUpperCase();
        }
    }
    // Collection of players after going through search filter
    self.filteredTestsuites = ko.computed(function () {
        var reg;
        // If many white spaces in a row, replace with only one white space
        fText = self.filterText().replace(/\s+/gi, '|');
        fText = fText.replace(/\|\s*$/gi, '');
        console.log("regex:", fText);
        reg = new RegExp(fText, "gi");
        // If there is anything in the search box, filter for this
        // As of now this does not divide the filterText and only searches the Name field
        var filteredCollection = ko.utils.arrayFilter(self.players(), function(test) {
            if(fText.length)
                return test.search_content.match(reg);
            else
                return 1;
        });

        return filteredCollection;
    }, self);
    /* script Ends with text search */


    /* script for sorting */
    //#region Sorting methods
    self.sortClick = function (column) {
        try {
            // Call this method to clear the state of any columns OTHER than the target
            // so we can keep track of the ascending/descending
            self.clearColumnStates(column);

            // Get the state of the sort type
            if (column.state() === "" || column.state() === self.descending) {
                column.state(self.ascending);
            }
            else {
                column.state(self.descending);
            }

            console.log(column.state());
            console.log(column.type);

            switch (column.type) {
                case "number":
                    self.numberSort(column);
                    break;
                case "date":
                    self.dateSort(column);
                    break;
                case "string":
                default:
                    self.stringSort(column);
                    break;
            }
        }
        catch (err) {
            // Always remember to handle those errors that could occur during a user interaction
            alert(err);
        }
    };

    // Generic sort method for numbers and strings
    self.stringSort = function (column) { // Pass in the column object

        self.players(self.players().sort(function (a, b) {

            // Set strings to lowercase to sort properly
            var playerA = a[column.property].toLowerCase(), playerB = b[column.property].toLowerCase();
            if (playerA < playerB) {
                return (column.state() === self.ascending) ? -1 : 1;
            }
            else if (playerA > playerB) {
                return (column.state() === self.ascending) ? 1 : -1;
            }
            else {
                return 0
            }
        }));
    };

    self.numberSort = function (column) {
        self.players(self.players().sort(function (a, b) {

            var playerA = a[column.property], playerB = b[column.property];
            if (column.state() === self.ascending) {
                return playerA - playerB;
            }
            else {
                return playerB - playerA;
            }
        }));

    };

    // Sort by date
    self.dateSort = function (column) {

        self.players(self.players().sort(function (a, b) {

            if (column.state() === self.ascending) {
                return new Date(a[column.property]) - new Date(b[column.property]);
            }
            else {
                return new Date(b[column.property]) - new Date(a[column.property]);
            }
        }));
    };

    //#region Utility Methods
    self.clearColumnStates = function (selectedColumn) {
        var otherColumns = self.columns().filter(function (col) {
            return col != selectedColumn;
        });

        for (var i = 0; i < otherColumns.length; i++) {
            otherColumns[i].state("");
        }
    };
    /* script Ends for sorting */

};

ko.applyBindings(new PlayersViewModel());

他们应该正确地在表格中执行搜索过滤和排序,如何为样本创建分页,它们不会影响搜索过滤器和表格中的排序。

1 个答案:

答案 0 :(得分:0)

使用ko.pureComputed分页的基础知识:

const paginatedData = ko.pureComputed(
  () => dataSource().slice(
    currentPage() * pageSize(),
    currentPage() * pageSize() + pageSize()
  )
);

在您的具体情况中,dataSourcefilteredTestsuitescurrentPageCurrentPagepageSizeDataPerPage

要记住的事情:   - 将currentPage的下限修改为0   - 将currentPage的上限修改为Math.floor(dataSource().length)   - 确保当dataSource长度发生变化时(即过滤时),更新currentPage以匹配新限制   - 确保当pageSize变大时,currentPage会更新以符合新限制。

&#13;
&#13;
const currentPage = ko.observable(0);
const pageSize = ko.observable(5);

const dataSource = ko.observableArray(
  Array.from({ length: 100 }, (_, i) => i)
);

const paginatedData = ko.pureComputed(
  () => dataSource().slice(
    currentPage() * pageSize(),
    currentPage() * pageSize() + pageSize()
  )
);

ko.applyBindings({
  next: () => currentPage(currentPage() + 1),
  prev: () => currentPage(currentPage() - 1),
  currentPage,
  paginatedData
});
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<ul data-bind="foreach: paginatedData">
  <li data-bind="text: $data"></li>
</ul>

<button data-bind="click: prev">&lt;</button>
<span data-bind="text: currentPage"></span>
<button data-bind="click: next">&gt;</button>
&#13;
&#13;
&#13;