Knockout Grid - Loading Remote Data
http://wijmo.com/grid-with-knockout-viewmodel-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.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!