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.

Knockout Grid - Loading Remote Data的更多相关文章

  1. fastboot 刷system.img 提示 sending 'system' (*KB)... FAILED (remote: data too large)

    华为G6-C00卡刷提示OEMSBL错误,只能线刷 ,但是官方找不到线刷img镜像,无奈 网上下了个可以线刷的工具套件 流氓ROM . 使用HuaweiUpdateExtractor(工具百度)把官方 ...

  2. Open Flash Chart IO ERROR Loading test data Error #2032

    http://blog.sina.com.cn/s/blog_6754464e0100qfvd.html Open Flash Chart 2 提示Open Flash Chart IO ERROR ...

  3. [GraphQL] Query Local and Remote Data in Apollo Link State

    In this lesson, you will learn how to query local and remote data in Apollo Link State in the same c ...

  4. [Vue-rx] Cache Remote Data Requests with RxJS and Vue.js

    A Promise invokes a function which stores a value that will be passed to a callback. So when you wra ...

  5. rdo(remote data objects) repo openstack icehouse

    problem making ssl connection Error: Cannot retrieve repository metadata (repomd.xml) for repository ...

  6. Js: Extensible Calendar Examples

    http://ext.ensible.comhttps://github.com/bmoeskau/Extensiblehttps://github.com/TeamupCom/extensibleh ...

  7. Jquery easyui 教程

            Jquery easyui教程                 目  录 1基本拖放... 4 2构建购物车型拖放... 5 3创建课程表... 8 4菜单和按钮Menu and Bu ...

  8. 基于 Angular Material 的 Data Grid 设计实现

    自 Extensions 组件库发布以来,Data Grid 成为了使用及咨询最多的组件.最开始 Data Grid 的设计非常简陋,经过一番重构,组件质量有了质的提升. Extensions 组件库 ...

  9. 【RDA】使用RDA(Remote Diagnostic Agent)工具对数据库进行健康检查

    [RDA]使用RDA(Remote Diagnostic Agent)工具对数据库进行健康检查 分类: Linux RDA英文全称叫做"Oracle Remote Diagnostic Ag ...

随机推荐

  1. 【转】【WPF】MVVM模式的3种command

    1.DelegateCommand 2.RelayCommand 3.AttachbehaviorCommand 因为MVVM模式适合于WPF和SL,所以这3种模式中也有一些小差异,比如RelayCo ...

  2. Navi.Soft20.WinCE使用手册

    1.概述 1.1应用场景 随着物联网的普及,越来越多的制造商对货品从原料配备,加工生产,销售出库等环节的要求和把控越来越高.在此情况之下,传统的ERP软件已经无法满足现有的流程. 移动设备的应用,在很 ...

  3. Go Walk教程 - 流程控制( switch)

    Go的 switch 非常灵活,表达式不必是常量或整数,执行的过程从上至下,直到找到匹配项,不要break: var score =98 var result string switch score/ ...

  4. scala学习之第三天:数组的特性与使用技巧

    1.数组 Scala数组与Scala序列是兼容的 - 在需要Seq[T]的地方可由Array[T]代替.最后,Scala数组支持所有的序列操作. 隐式转换 方法1:通过scala.collection ...

  5. Java6 String.substring()方法的内存泄露

    substring(start,end)在Java编程里面经常使用,没想到如果使用不当,会出现内存泄露. 要了解substring(),最好的方法便是查看源码(jdk6): /** * <blo ...

  6. 基于.Net FrameWork的 RestFul Service

    关于本文 这篇文章的目的就是向大家阐述如何在.net framework 4.0中创建RestFul Service并且使用它. 什么是web Services,什么是WCF 首先讲到的是web Se ...

  7. GDB深入研究

    GDB深入研究 一.GDB代码调试 (一)GDB调试实例 在终端中编译一个示例C语言小程序,保存到文件 gdb-sample.c 中,用GCC编译之 #include <stdio.h> ...

  8. UIButton利用分类扩展方法(封装)

    UIButton+BackgroundColor.h #import <UIKit/UIKit.h> @interface UIButton (BackgroundColor) - (vo ...

  9. .net截取两个字符串中间的内容

    做模拟登录时,需要截取html代码中的名字,返回的字符串内容如下 <span class="welcome">您好<span style="font-s ...

  10. 编写高质量代码改善C#程序的157个建议[用抛异常替代返回错误、不要在不恰当的场合下引发异常、重新引发异常时使用inner Exception]

    前言 自从.NET出现后,关于CLR异常机制的讨论就几乎从未停止过.迄今为止,CLR异常机制让人关注最多的一点就是“效率”问题.其实,这里存在认识上的误区,因为正常控制流程下的代码运行并不会出现问题, ...