Skip to main content Skip to footer

Knockout Grid - Loading Remote Data

We were hearing quite a few people asking how to best create a knockout ViewModel for our Grid with data fetched from a remote service. In order to help guide people through this scenario, we sat down and built an implementation. Along the way we added some features (as of Wijmo 2.2.0) to the Grid to make this even easier. Follow along to build your own Grid ViewModel using knockout. You can also see the knockout Grid demo online.

Add JavaScript & CSS Dependencies

Add the following dependencies to your page: jQuery, jQuery UI, Wijmo & Knockout.

<!-- jQuery -->  
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>  
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.23/jquery-ui.min.js"></script>  
<!-- Wijmo CSS and script -->  
<link type="text/css" href="http://cdn.wijmo.com/themes/metro/jquery-wijmo.css" rel="stylesheet" title="metro-jqueryui" />  
<link type="text/css" href="http://cdn.wijmo.com/jquery.wijmo-complete.all.2.2.0.min.css" rel="stylesheet" />  
<script type="text/javascript" src="http://cdn.wijmo.com/jquery.wijmo-open.all.2.2.0.min.js"></script>  
<script type="text/javascript" src="http://cdn.wijmo.com/jquery.wijmo-complete.all.2.2.0.min.js"></script>  
<!-- KnockoutJS for MVVM-->  
<script type="text/javascript" src="http://cdn.wijmo.com/external/knockout-2.1.0.js"></script>  
<script type="text/javascript" src="http://cdn.wijmo.com/external/knockout.wijmo.js"></script>

Create the ViewModel

Now we need to create the ViewModel for our Grid. This is where all the magic is. Our ViewModel is tailored to the Grid and has properties that the Grid will bind to for its options. The load method will be called from outside the ViewModel when new data is needed from the server. This web service happens to be an OData service, but any service type can be used here.

//Create ViewModel  
var viewModel = {  
    pageSize: ko.observable(10),  
    pageIndex: ko.observable(0),  
    sortCommand: ko.observable("ProductID asc"),  
    dataRows: ko.observableArray([]),  
    totalRows: ko.observable(0),  
    sorted: function (e, data) {  
        viewModel.sortCommand(data.sortCommand);  
    },  
    paged: function (e, data) {  
        viewModel.pageIndex(data.newPageIndex);  
    },  
    load: function () {  
        $.ajax({  
            url: "http://services.odata.org/Northwind/Northwind.svc/Products",  
            dataType: "jsonp",  
            jsonp: "$callback",  
            data: {  
                $format: "json",  
                $inlinecount: "allpages",  
                $select: "ProductID,ProductName,UnitPrice,UnitsInStock",  
                $orderby: viewModel.sortCommand(),  
                $top: viewModel.pageSize(),  
                $skip: viewModel.pageIndex() * viewModel.pageSize(),  
                "paging[pageIndex]": viewModel.pageIndex(),  
                "paging[pageSize]": viewModel.pageSize()  
            },  
            success: function (result) {  
                var data = result.d.results;  
                var arr = [];  

                $.each(data, function (i) {  
                    arr.push(new product(data[i]));  
                });  
                viewModel.totalRows(result.d.__count);  
                viewModel.dataRows(arr);  
            }  
        });  
    }  

};  

//Class constructor for grid row. Returns observable properties.  
var product = function (data) {  
    return {  
        ProductID: ko.observable(data.ProductID),  
        ProductName: ko.observable(data.ProductName),  
        UnitPrice: ko.observable(data.UnitPrice),  
        UnitsInStock: ko.observable(data.UnitsInStock)  
    };  
};

Create the View

This markup is really simple. We are just adding a Wijmo Dropdown (select) and Grid (table) to the page and binding their options to the ViewModel.

<div class="toolbar">  
<label>Display: </label>  
<select data-bind="value: pageSize, wijdropdown: {}">  
<option value="5">5</option>  
<option value="10">10</option>  
<option value="20">20</option>  
</select>  
</div>  
<table id="dataGrid" data-bind="  
wijgrid: {  
data: dataRows,  
pageSize: pageSize,  
pageIndex: pageIndex,  
totalRows: totalRows,  
allowPaging: true,  
allowSorting: true,  
sorted: sorted,  
pageIndexChanged: paged,  
columns: [  
{ sortDirection: 'ascending', dataType: 'number', dataFormatString: 'n0', headerText: 'ID', width: 60 },  
{ headerText: 'Product' },  
{ dataType: 'currency', headerText: 'Price', width: 100},  
{ dataType: 'number', dataFormatString: 'n0', headerText: 'Units', width: 100}]  
}">  
</table>

Initializing the App

Now the we have a ViewModel and View, we can initialize the app. This code initializes the KO bindings and adds listeners for critical components of the ViewModel in order to call the load() method when new data is needed.

//Bind ViewModel and Event Handlers  
$(document).ready(function () {  
    ko.applyBindings(viewModel);  
    viewModel.load();  
    viewModel.sortCommand.subscribe(function (newValue) {  
        viewModel.load();  
    });  
    viewModel.pageIndex.subscribe(function (newValue) {  
        viewModel.load();  
    });  
    viewModel.pageSize.subscribe(function (newValue) {  
        viewModel.load();  
        $(":wijmo-wijdropdown").wijdropdown("refresh");  
    });  
});

Run It!

That's it, just run your app and you have a Grid that fetches remote data when paging and sorting. You could also add other widgets to the app and bind to the same data in the ViewModel. This is the ideal solution for using knockout and the Wijmo Grid. This demo is included in the download under Wijmo-Complete/development-bundle/demo-apps/knockout-grid. You can also play with the live version of this knockout Grid demo online.

Chris Bannon - Global Product Manager

Chris Bannon

Global Product Manager of Wijmo
comments powered by Disqus