Kendo 的数据源支持本地数据源(JavaScript 对象数组),或者远程数据源(XML, JSON, JSONP),支持CRUD操作(创建,读取,更新和删除操作),并支持排序,分页,过滤,分组和集合等。
准备开始
下面创建一个本地数据源。
1 |
var movies = [ {
|
2 |
title: "Star Wars: A New Hope" ,
|
3 |
year: 1977
|
4 |
}, {
|
5 |
title: "Star Wars: The Empire Strikes Back" ,
|
6 |
year: 1980
|
7 |
}, {
|
8 |
title: "Star Wars: Return of the Jedi" ,
|
9 |
year: 1983
|
10 |
}
|
11 |
]; |
12 |
var localDataSource = new kendo.data.DataSource({data: movies});
|
创建一个远程数据源 (Twitter)
1 |
var dataSource = new kendo.data.DataSource({
|
2 |
transport: {
|
3 |
read: {
|
4 |
// the remote service url
|
5 |
url: "http://search.twitter.com/search.json" ,
|
6 |
7 |
// JSONP is required for cross-domain AJAX
|
8 |
dataType: "jsonp" ,
|
9 |
10 |
// additional parameters sent to the remote service
|
11 |
data: {
|
12 |
q: "html5"
|
13 |
}
|
14 |
}
|
15 |
},
|
16 |
// describe the result format
|
17 |
schema: {
|
18 |
// the data which the data source will be bound to is in the "results" field
|
19 |
data: "results"
|
20 |
}
|
21 |
}); |
绑定数据源到UI组件
Kendo UI组件很多都支持数据绑定 ,UI组件绑定的数据源可以在配置UI组件时设置,或是多个UI组件共享同一个数据源。
创建UI组件时设置DataSource属性
1 |
$( "#chart" ).kendoChart({
|
2 |
title: {
|
3 |
text: "Employee Sales"
|
4 |
},
|
5 |
dataSource: new kendo.data.DataSource({
|
6 |
data: [
|
7 |
{
|
8 |
employee: "Joe Smith" ,
|
9 |
sales: 2000
|
10 |
},
|
11 |
{
|
12 |
employee: "Jane Smith" ,
|
13 |
sales: 2250
|
14 |
},
|
15 |
{
|
16 |
employee: "Will Roberts" ,
|
17 |
sales: 1550
|
18 |
}]
|
19 |
}),
|
20 |
series: [{
|
21 |
type: "line" ,
|
22 |
field: "sales" ,
|
23 |
name: "Sales in Units"
|
24 |
}],
|
25 |
categoryAxis: {
|
26 |
field: "employee"
|
27 |
}
|
28 |
}); |
使用共享的远程数据源
1 |
var sharableDataSource = new kendo.data.DataSource({
|
2 |
transport: {
|
3 |
read: {
|
4 |
url: "data-service.json" ,
|
5 |
dataType: "json"
|
6 |
}
|
7 |
}
|
8 |
}); |
9 |
10 |
// Bind two UI widgets to same DataSource |
11 |
$( "#chart" ).kendoChart({
|
12 |
title: {
|
13 |
text: "Employee Sales"
|
14 |
},
|
15 |
dataSource: sharableDataSource,
|
16 |
series: [{
|
17 |
field: "sales" ,
|
18 |
name: "Sales in Units"
|
19 |
}],
|
20 |
categoryAxis: {
|
21 |
field: "employee"
|
22 |
}
|
23 |
}); |
24 |
25 |
$( "#grid" ).kendoGrid({
|
26 |
dataSource: sharableDataSource,
|
27 |
columns: [
|
28 |
{
|
29 |
field: "employee" ,
|
30 |
title: "Employee"
|
31 |
},
|
32 |
{
|
33 |
field: "sales" ,
|
34 |
title: "Sales" ,
|
35 |
template: '#= kendo.toString(sales, "N0") #'
|
36 |
}]
|
37 |
}); |
这个例子使用了模板 template ,模板的用法参见后面的文章。