Knockout pagination techniques

Here is a way I have been able to successfully bind JSON data:

The JSON file I am working with

$(document).ready(function () {

    var jsondata = JSON.parse(var1);
    DisplayFields = function (jsondata) {
        var viewModel = {
            d: ko.observableArray(jsondata),
            pageSize: ko.observable(10),
            pageIndex: ko.observable(0),
            previousPage: function () {
                this.pageIndex(this.pageIndex() - 1);
            },
            nextPage: function () {
                this.pageIndex(this.pageIndex() + 1);
            }
        };
        viewModel.maxPageIndex = ko.dependentObservable(function () {
            return Math.ceil(this.d().length / this.pageSize()) - 1;
        }, viewModel);
        viewModel.pagedRows = ko.dependentObservable(function () {
            var size = this.pageSize();
            var start = this.pageIndex() * size;
            return this.d().slice(start, start + size);
        }, viewModel);
        ko.applyBindings(viewModel, document.getElementById("Datasection"));
        ko.applyBindings(viewModel, document.getElementById("prevnext"));
    };
    DisplayFields(jsondata);    
});

The HTML file I am using

    <section class="col-lg-12 paddingBottom40 paddingTop20 RecentInnovation" id="Datasection" data-bind='template: { foreach: pagedRows }'>
        <div class="row">
            <section class="col-lg-1 col-md-1 col-sm-1 col-xs-4">
                <div class="bgOrange blue text-center paddingTop10 paddingBottom10">
                    <span class="size18" data-bind="text: Views"></span>
                    <br>
                    View
                </div>
            </section>
            <section class="col-lg-9 col-md-9 col-sm-9 col-xs-12">
                <a data-bind="attr: { href: '../SitePages/IdeaDetails.aspx?ideaid=' + ID }" class="size14 green"><strong><span data-bind="    text: BusinessProblem"></span></strong></a>
                <br>
                <p class="paddingTop5">Category:<span data-bind="text: InnovationType" class="green"></span>&nbsp;&nbsp;Submitted by: <span data-bind="    text: Requester" class="green"></span>&nbsp;&nbsp;On <span data-bind="    text: Created " class="green"></span></p>
                <p class="paddingTop5">Tags: <span data-bind="text: Keywords" class="green"></span>&nbsp;&nbsp&nbsp;Domain: <span data-bind="    text: Domain" class="green"></span>&nbsp;&nbsp&nbsp;SubDomain: <span data-bind="    text: SubDomain" class="green"></span></p>
            </section>
            <section class="col-lg-2 col-md-2 col-sm-2 col-xs-12 text-right"><span data-bind="text: Status"></span><span data-bind="    css: statusCss"></span></section>
        </div>

    </section>

I am looking to implement pagination on my page with direct links to each page. How can I modify the JavaScript code above to achieve this?

Thank you for any help.

Answer №1

Code Snippet:

<span data-bind="with: previousLink">
    <a data-bind="attr: { href: href }, click: $parent.sendPrevPage" title="Previous Page">Go to Previous Page</a>
</span>
<span data-bind="with: nextLink">
    <a data-bind="attr: { href: href }, click: $parent.sendNextPage" title="Next Page">Go to Next Page</a>
</span>

JavaScript Function:

function LinkViewModel(model) {
    model = model || {};
    var self = this;
    self.href = model.Href || ' ';
    self.rel = model.Rel || ' ';
}

executeLink = function (linkVm) {
    $.ajax({
        url: linkVm.href,
        type: "GET",
        success: function (response) {
            //carry out necessary actions
        },
        error: function (xhr, ajaxOptions, thrownError) {
            //handle errors appropriately
        }
    });
}

self.sendPrevPage = function () {
    executeLink(self.previousLink());
};

self.sendNextPage = function () {
    executeLink(self.nextLink());
};

Answer №2

Check out this super basic example:

HTML:

<div data-bind="foreach: pageNumbers">
    <a data-bind="click: $root.gotoPage, text: pageNumber"></a>
    &nbsp;&nbsp;
</div>

Javascript:

var viewModel = function(){
    var self = this;
    self.maxPageIndex = ko.observable(10);
    self.pageNumbers = ko.computed(function() {
        var pages = [];
        for (i=1; i<=self.maxPageIndex(); i++){
            pages.push({pageNumber: i});
        }
        return pages;
    });
    self.gotoPage = function(page){
        console.log("Navigate to page " + page.pageNumber);
    };
};

ko.applyBindings(new viewModel());

Notice that knockout automatically passes the object ('page' in this case) into the click function. No extra setup needed, just call the click function from the $root and it will pass in the object from the loop's scope... I find that pretty neat, but hey, I'm a nerd like that!

Fiddle: http://jsfiddle.net/brettwgreen/jp6hu5ho/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing a template value in my AngularJS/Ionic Framework code to not be replaced properly?

Recently, I've been exploring the world of Ionic Framework with Angular by my side. However, I've hit a bit of a roadblock. My goal is to set up tabs at the bottom of my application using a model definition. Here's what I've tried so ...

What is an alternative approach to passing arguments to an event handler in a React render component without using a lambda function?

In my React app, I've learned that using lambda functions in the property of a render component can harm application performance. For example: <ConfirmSmsModal modal={args.modal} smsCheck={async (code: string) => { return await this._vm ...

Ways to accomplish a task prior to form submission without relying on preventDefault

How can I perform an action before form submission without using e.preventDefault();? I am faced with a situation where I have two form buttons and need to set a hidden field value before submitting the form. In my Symfony2 framework, when I submit the fo ...

The iPhone webview keyboard causes the layout to be pushed upward and remain elevated

While editing text fields, the native keyboard pops up and stays visible in the webview. It's almost like leaving the toilet seat up! Is there a way to return to the original scroll position after the native keyboard disappears? Perhaps an event that ...

Retrieve JSON data from an API through XSLT transformation

My goal is to retrieve a JSON file from an API using XSLT 3. In Python, I could achieve this with the following code snippet: import urllib.request, json with urllib.request.urlopen("http://dme-intern.mozarteum.local/digital-editions/api/work ...

Dynamic CSS manipulation with jQuery: Generate and access styles on the fly

I am working on an application where I am utilizing jQuery along with maphilight for highlighting image map segments. In addition to this functionality, I want to dynamically highlight specific HTML elements based on mouseover/mouseout events for the image ...

Updating user interface dynamically based on the most recent data stream is crucial for a seamless user experience

I am facing a challenge where I need to update the indicator in the user interface based on real-time data. The requirement is that if there has been no data received in the last 30 seconds, the indicator should turn red. However, if data is received withi ...

Streamlining with jQuery Mobile and JSON data

Hello everyone, I have a few inquiries about implementing jQuery Mobile and JSON. I am interested in developing a mobile application for a website that currently doesn't have a JSON plugin installed, and I have these two specific questions: How can ...

Slow down while confirming the server's status using jquery

Currently, I am working on a project that requires me to constantly monitor the online status of my application's server. After extensive research, I finally found a script that seemed to do the job. However, there is one issue - when I disconnect the ...

Using React to Identify the Chosen Option on a Custom Toggle Button

I have successfully implemented a toggle switch using HTML and CSS in my React app. I am now looking for a way to detect the selected option whenever it changes. For instance, if OR is chosen, I would like it to be saved in the selectedOption state, and if ...

Switch the <div> depending on the dropdown option chosen

@Html.DropDownList("Category", @Model.Select(item => new SelectListItem { Value = item.Id.ToString(), Text = item.Name.ToString(), Selected = "select" == item.Id.ToString() }), new { @class = "form-control", id = "dropDownList ...

How to pause a loop temporarily before proceeding with the next iteration

I am facing a challenge where I want to trigger two events simultaneously, but only one event should be allowed to continue at a time. If an event is already in progress, I need the ability to forcefully stop it and allow the other event to take control. S ...

When trying to parse JSON data from the server, I encountered an issue where the type 'String' was not recognized as a subtype of 'Map<String, dynamic>'. However, I found that hardcoding the data allowed

While attempting to extract data from a JSON object on a web source, I encountered an error. Despite ensuring that my application can retrieve information from the server, it appears that there may be an error in how I structured my model. Here is the stru ...

Recording videos using the Safari Browser

Within my ReactJs application, I have integrated react-multimedia-capture, a package that utilizes navigator.mediaDevices.getUserMedia and the MediaRecorder API to facilitate video recording. While I am successfully able to record videos on Chrome, Safari ...

Functionality of the Parameters Object

As I transition from using the params hash in Rails to learning Node/Express, I find myself confused about how it all works. The Express.js documentation provides some insight: 'This property is an array containing properties mapped to the named rout ...

When utilizing AJAX XMLHttpRequest, the concatenated response text from Symfony's StreamedResponse becomes apparent

Below is the code for a controller that returns Line 1 as soon as the endpoint is called and then two seconds later it returns Line 2. When accessing the URL directly at http://ajax.dev/app_dev.php/v2, everything works as expected. /** * @Method({"GET"}) ...

Choosing the Following Date from the Datepicker using Selenium IDE

I need the selenium IDE test case to automatically select a date following the steps outlined below: Start by clicking on the departure date to open the datepicker Loop through the dates starting with the currently selected day until the next available d ...

Not receiving success response from JQuery Ajax

This is the code I'm working with: $.ajax({ type:"get", //this doesn't work //url:'http://example.com/json.php', //But this works url:'http://api.flickr.com/services/fe ...

Why does console.log in JavaScript exhibit different behaviors as evidenced by the code?

Exploring the behavior of console.log(obj) compared to console.log("obj"+"\n"+obj) in the code snippet below reveals two distinct output outcomes. const obj = new Object() obj.first = 'John' obj.last = 'Doe' obj.alive = true ob ...

What is the process for transforming a string into a Cairo felt (field element)?

In order to work with Cairo, all data must be represented as a felt. Learn more here Is there a way to convert a string into a felt using JavaScript? ...