Skip to content Skip to sidebar Skip to footer

Iterating Through A List Of Users And Pushing To An Array In Knockout

I have this script that returns a list of all users. I would like to have: set the viewModel's totalUsers and page properties based on data returned. Iterate through the list of u

Solution 1:

HEre you go. I have mimicked the getRoster ajax call for the fiddle. in your case, you will be making a "GET" call and not a "POST".

http://jsfiddle.net/sujesharukil/z8vpx/4/

rosterArray is the main observableArray that will store the entire list from the server, filteredRoster will get the data from the rosterArray based on the currentPage, toDisplay stores the limit, currentPage tracks the current page, totalRoster is computed that returns the total elements in the array

var rosterArray = ko.observableArray(),
    currentPage = ko.observable(1),
    toDisplay = ko.observable(20),
    filteredRoster = ko.computed(function(){
        var init = (currentPage() - 1) * toDisplay(),
            filteredList = [],
            rosterLength = rosterArray().length,
            displayLimit = toDisplay();

        if(rosterLength === 0)
            return [];

        for(var i = init; i < (displayLimit + init) - 1 && i < rosterLength; i++){
            filteredList.push(rosterArray()[i]);
        }

        return filteredList;
    }),
    totalRoster = ko.computed(function(){
        return rosterArray().length;
    }),
    changePage = function(data){
        currentPage(data);
    },
    next = function(){
        if((currentPage() * toDisplay()) > rosterArray().length)
            return;

        currentPage(currentPage() + 1);
    },
    prev = function(){
        if(currentPage() === 1)
            return;

        currentPage(currentPage() - 1);
    };

Hope that helps.

-Suj


Post a Comment for "Iterating Through A List Of Users And Pushing To An Array In Knockout"