目前网络上大多数的文章都是基于老版本的jsgrid,无法使用并容易误导读者,因此开始翻译官文.
才疏学浅,如果不妥敬请谅解
翻开始于
一次 2020-11-8 23:26:33
二次2020-11-9 09:17:20
配置
config对象包含以下选项(默认值在下面指定)
{
fields: [],
data: [],
autoload: false,
controller: {
loadData: $.noop,
insertItem: $.noop,
updateItem: $.noop,
deleteItem: $.noop
},
width: "auto",
height: "auto",
heading: true,
filtering: false,
inserting: false,
editing: false,
selecting: true,
sorting: false,
paging: false,
pageLoading: false,
rowClass: function(item, itemIndex) { ... },
rowClick: function(args) { ... },
rowDoubleClick: function(args) { ... },
noDataContent: "Not found",
confirmDeleting: true,
deleteConfirm: "Are you sure?",
pagerContainer: null,
pageIndex: 1,
pageSize: 20,
pageButtonCount: 15,
pagerFormat: "Pages: {first} {prev} {pages} {next} {last} {pageIndex} of {pageCount}",
pagePrevText: "Prev",
pageNextText: "Next",
pageFirstText: "First",
pageLastText: "Last",
pageNavigatorNextText: "...",
pageNavigatorPrevText: "...",
invalidNotify: function(args) { ... }
invalidMessage: "Invalid data entered!",
loadIndication: true,
loadIndicationDelay: 500,
loadMessage: "Please, wait...",
loadShading: true,
updateOnResize: true,
rowRenderer: null,
headerRowRenderer: null,
filterRowRenderer: null,
insertRowRenderer: null,
editRowRenderer: null
}
字段
网格的字段(列)数组。
根据字段类型,每个字段都有常规选项和特定选项。
所有字段类型特有的常规选项:
{
type: "",
name: "",
title: "",
align: "",
width: 100,
visible: true,
css: "",
headercss: "",
filtercss: "",
insertcss: "",
editcss: "",
filtering: true,
inserting: true,
editing: true,
sorting: true,
sorter: "string",
headerTemplate: function() { ... },
itemTemplate: function(value, item) { ... },
filterTemplate: function() { ... },
insertTemplate: function() { ... },
editTemplate: function(value, item) { ... },
filterValue: function() { ... },
insertValue: function() { ... },
editValue: function() { ... },
cellRenderer: null,
validate: null
}
- type 是字段注册表中字段(
"text"|"number"|"checkbox"|"select"|"textarea"|"control"
)的字符串键jsGrid.fields
(可以使用自定义字段类型轻松扩展)。 - name 是与列关联的数据项的属性。
- title 是要显示在列头中的文本。如果未指定,则将使用 name。
- align 是单元格中文本的对齐方式。接受以下值
"left"|"center"|"right"
。 - width 列的宽度。
- visible 是一个布尔值,指定是否显示列。(新增版本:1.3)
- css 是一个字符串,表示要附加到表单元格的css类。
- headercss是一个字符串,表示要附加到表头单元格的css类。
- filtercss 是一个字符串,表示要附加到表filter行单元格的css类。
- insertcss 是一个字符串,表示要附加到表insert行单元格的css类。
- editcss 是一个字符串,表示要附加到表edit行单元格的css类。
- filtering 是一个布尔值,指定列是否有过滤(
filterTemplate()
被呈现,filterValue()
包含在过滤项目对象中)。?? - inserting 是一个布尔值,指定列是否有(
insertTemplate()
被呈现,insertValue()包含在插入项目中)?? - editing 是一个布尔值,指定列是否具有编辑功能(editTemplate()被呈现,editValue()包含在编辑项中)。??
- sorting 是一个布尔值,指定列是否具有排序能力。
- sorter 是一个字符串或函数,指定如何按字段对项目进行排序。字符串是注册表中排序策略的键
jsGrid.sortStrategies
(可以使用自定义排序函数)。排序函数具有签名function(value1, value2) { return -1|0|1; }
。 - headerTemplate 是一个创建列标题内容的函数。它应该以string、DomNode或jQueryElement的形式返回标记。
- itemTemplate 是一个创建单元格内容的函数。它应该以string、DomNode或jQueryElement的形式返回标记。函数签名是function(value,item),其中value是数据项column属性的值,item是行数据项。
- filterTemplate 是一个用于创建筛选行单元格内容的函数。它应该以string、DomNode或jQueryElement的形式返回标记。
- insertTemplate 是一个创建插入行单元格内容的函数。它应该以string、DomNode或jQueryElement的形式返回标记。
- editTemplate 是创建编辑行单元格内容的函数。它应该以string、DomNode或jQueryElement的形式返回标记。函数签名是function(value,item),其中value是数据项column属性的值,item是行数据项。
- filterValue 是一个函数,返回与列关联的filter属性的值。
- insertValue 是一个函数,返回与列关联的插入项属性的值。
- editValue 是一个函数,返回与列关联的编辑项属性的值。
- cellRenderer 是自定义渲染器的函数。函数签名是
function(value, item)
,其中value是数据项column属性的值,item是行数据项。函数应该以字符串、jQueryElement或表示表单元格td的DomNode返回标记。 - validate 是一个字符串,用作验证规则名称或验证函数、验证配置对象或验证配置对象数组。阅读验证部分中有关验证的更多详细信息。链接 Validation section.
特定字段选项取决于具体字段类型。阅读“网格字段”部分中的内置字段。
data
要在网格中显示的数据值。该选项应用于提供静态数据。使用controller
选项提供非静态数据。
autoload (default false
)
一个布尔值,指定controller
.loadData将在渲染网格时调用。
controller
返回具有以下结构的对象或函数:
{
loadData: $.noop,
insertItem: $.noop,
updateItem: $.noop,
deleteItem: $.noop
}
- loadData 是一个返回数据数组或jQuery promise的函数,该数组将用一个数据数组来解析(当pageLoading为true而不是object时,应该返回结构{data:[items],itemsCount:[total items count]})。当pageLoading为true时接受筛选器参数,包括当前筛选器选项和分页参数。
- insertItem 是一个返回inserted item或jQuery promise的函数,它将通过inserted item进行解析。接受插入项对象。
- updateItem 是一个返回updated item或jQuery promise的函数,它将用updated item解析。接受更新项对象。
- deleteItem 是一个删除项的函数。返回jQuery promise,删除完成后将解析该承诺。接受删除项对象。
在网格控制器部分阅读更多关于控制器接口的信息。链接 Grid Controller
width (default: "auto"
)
指定grid的总宽度。接受接受的所有值类型jQuery.width.
height (default: "auto"
)
指定grid的总高度。接受接受的所有值类型jQuery.height.
heading (default: true
)
布尔值指定是否显示grid表头
filtering (default: false
)
布尔值指定是否显示筛选器行。
inserting (default: false
)
A boolean value specifies whether to show inserting row or not.
editing (default: false
)
布尔值指定是否显示插入行。
selecting (default: true
)
布尔值指定悬停时是否亮显grid行。
sorting (default: false
)
布尔值指定是否允许排序。
paging (default: false
)
布尔值指定是否按页显示数据。
pageLoading (default: false
)
布尔值指定是否按页加载数据。当pageLoading为true时,控制器的loadData方法接受带有两个附加属性pageSize和pageIndex的筛选器参数。
rowClass
指定行css类的字符串或函数。字符串包含用空格分隔的类。函数具有签名function(item, itemIndex)
。它接受数据项和项的索引。它应该返回一个包含用空格分隔的类的字符串。
rowClick
处理行单击的函数。接受具有以下结构的单个参数:
{
item // data item
itemIndex // data item index
event // jQuery event
}
默认情况下 rowClick
执行行编辑时 editing 为
true
.
rowDoubleClick
函数处理行双击。接受具有以下结构的单个参数:
{
item // data item
itemIndex // data item index
event // jQuery event
}
noDataContent (default "Not found"
)
返回标记、jQueryElement或DomNode的字符串或函数,指定当数据为空数组时要显示的内容。
confirmDeleting (default true
)
一个布尔值,指定是否要求用户确认项目删除。
deleteConfirm (default "Are you sure?"
)
返回字符串的字符串或函数,指定要显示给用户的删除确认消息。函数具有签名 function(item)
并接受要删除的项。
pagerContainer (default null
)
jQueryElement或DomNode,用于指定在何处呈现。用于外部区域呈现。当它等于null时,会在grid的底部呈现。
pageIndex (default 1
)
指定当前页索引的整数值。仅当分页为 true 时应用。
pageSize (default 20
)
一个整数值,指定页面上的项目数。仅当分页为 true 时应用。
pageButtonCount (default 15
)
一个整数值,指定要显示的pager 按钮的最大数量。
pagerFormat
指定pager 格式的字符串。默认值为"Pages: {first} {prev} {pages} {next} {last} {pageIndex} of {pageCount}"
以下格式中可以使用占位符:
{first} // link to first page 第一页
{prev} // link to previous page 上一页
{pages} // page links 每页大小?
{next} // link to next page 下一页
{last} // link to last page 最后一页
{pageIndex} // current page index 当前页号
{pageCount} // total amount of pages 总页数
{itemCount} // total amount of items 总数量
pageNextText (default "Next"
)
指定指向下一页的链接的文本的字符串。
pagePrevText (default "Prev"
)
一个字符串,指定指向上一页的链接的文本。
pageFirstText (default "First"
)
指定指向第一页的链接的文本的字符串。
pageLastText (default "Last"
)
一个字符串,指定指向最后一页的链接的文本。
pageNavigatorNextText (default "..."
)
当页面总数超过pageButtonCount时,指定要移动到下一组页面链接的链接文本的字符串。
pageNavigatorPrevText (default "..."
)
当页面总数超过pageButtonCount时,指定要移动到上一组页面链接的链接文本的字符串.
invalidMessage (default "Invalid data entered!"
)
指定输入无效数据时警报消息文本的字符串。
invalidNotify
输入无效数据时触发的函数。默认情况下,所有违反验证程序的消息都会被警告。行为可以通过提供自定义函数进行定制。
函数接受具有以下结构的单个参数:
{
item // inserting/editing item
itemIndex // inserting/editing item index
errors // array of validation violations in format { field: "fieldName", message: "validator message" }
}
在以下示例中,将在控制台中打印错误消息,而不是发出警报:
$("#grid").jsGrid({
...
invalidNotify: function(args) {
var messages = $.map(args.errors, function(error) {
return error.field + ": " + error.message;
});
console.log(messages);
}
...
});
loadIndication (default true
)
一个布尔值,指定在控制器操作执行期间是否显示加载指示。
loadIndicationDelay (default 500
)
一个整数值,指定在显示负载指示之前的延迟(毫秒)。仅在loadIndication
is true
.时应用。
loadMessage (default "Please, wait..."
)
指定加载指示面板文本的字符串。仅当负载指示为真时应用。
loadShading (default true
)
一个布尔值,指定在加载指示期间是否在网格内容上显示覆盖(着色器)。仅loadIndication
is true
.时应用。
updateOnResize (default true
)
一个布尔值,指定是否在窗口调整大小事件时刷新grid。
rowRenderer (default null
)
A function to customize row rendering. The function signature is function(item, itemIndex)
, where item
is row data item, and itemIndex
is the item index. The function should return markup as a string, jQueryElement or DomNode representing table row tr
.
自定义行呈现的函数。函数签名是function(item, itemIndex),
where 项目是 is row data item 函数应该以字符串的形式返回标记,jQueryElement或DomNode表示 table row tr
。??
headerRowRenderer (default null
)
自定义grid标题行的函数。函数应该以字符串、jQueryElement或表示表行tr的DomNode返回标记。
filterRowRenderer (default null
)
自定义grid筛选器行的函数。函数应该以字符串、jQueryElement或表示表行tr的DomNode返回标记。
insertRowRenderer (default null
)
自定义grid插入行的函数。函数应该以字符串、jQueryElement或表示表行tr的DomNode返回标记。
editRowRenderer (default null
)
自定义编辑行渲染的函数。函数签名是function(item,itemIndex),其中item是行数据项,itemIndex是项索引。函数应该以字符串、jQueryElement或表示表行tr的DomNode返回标记。
pagerRenderer (default null
)
version added: 1.2
添加的版本:1.2
自定义pager呈现的函数。函数接受具有以下结构的单个参数:
{
pageIndex, // index of the currently opened page
pageCount // total amount of grid pages
}
函数应该以字符串、jQueryElement或表示pager的DomNode形式返回标记。如果指定了pagerRenderer,则pagerFormat选项将被忽略。
Grid Fields
网格支持的所有字段都存储在 jsGrid.fields对象,其中key是字段的一种类型,value是field类。
jsGrid.fields包含以下内置字段:
{
text: { ... }, // 简单文本输入simple text input
number: { ... }, // 数字输入number input
select: { ... }, // 选择控件select control
checkbox: { ... }, // 复选框输入checkbox input
textarea: { ... }, // textarea控件(呈现用于插入和编辑的文本区域和用于过滤的文本输入)textarea control (renders textarea for inserting and editing and text input for filtering) control: { ... } // 控制字段,数据行带有删除和编辑按钮,搜索和添加按钮用于筛选和插入行control field with delete and editing buttons for data rows, search and add buttons for filter and inserting row
}
每个内置字段可以使用字段部分中描述的常规配置属性和下面描述的自定义字段特定属性轻松地进行自定义。
text
文本字段在过滤器中呈现<input type=“Text”>插入和编辑行。
自定义属性:
{
autosearch: true, // 当用户在筛选器输入中按“回车”键时触发搜索triggers searching when the user presses `enter` key in the filter input
readOnly: false //布尔值定义输入是否为只读(在v1.4中添加)a boolean defines whether input is readonly (added in v1.4)
}
number
数字字段在过滤器中呈现<input type=“Number”>插入和编辑行。
自定义属性:
{
sorter: "number", // 使用数字展示uses sorter for numbers ??
align: "right", // 右文本对齐right text alignment
readOnly: false // 布尔值定义输入是否为只读(在v1.4中添加)a boolean defines whether input is readonly (added in v1.4)
}
select
在“过滤器”、“插入和编辑行”中选择“字段渲染 <select>
控制”。
自定义属性:
{ align: "center", // 文本居中对齐center text alignment
autosearch: true, // 当用户更改筛选器中的选定项时触发搜索triggers searching when the user changes the selected item in the filter
items: [], // 用于选择的项数组an array of items for select
valueField: "", // 要用作值的项的属性名称name of property of item to be used as value
textField: "", // 要用作显示值的项的属性名称name of property of item to be used as displaying value
selectedIndex: -1 // 默认为所选项目的索引index of selected item by default
valueType: "number|string", // 值的数据类型the data type of the value
readOnly: false //一个布尔值定义select是否为readOnly(在v1.4中添加)a boolean defines whether select is readonly (added in v1.4)
}
如果未定义valueField,则使用项索引。如果未定义textField,则使用项本身来显示值。
例如,简单的select字段配置可能如下所示:
{
name: "Country",
type: "select",
items: [ "", "United States", "Canada", "United Kingdom" ]
}
或更复杂的项目作为对象:
{
name: "Country",
type: "select"
items: [
{ Name: "", Id: 0 },
{ Name: "United States", Id: 1 },
{ Name: "Canada", Id: 2 },
{ Name: "United Kingdom", Id: 3 }
],
valueField: "Id",
textField: "Name"
}
valueType
定义字段值是应转换为数字还是作为字符串返回。选项的值根据第一个项的valueField的数据类型自动确定,但可以重写它。
checkbox
Checkbox字段在过滤器、插入和编辑行中呈现<input type=“Checkbox”>。Filter复选框支持的中间状态,因此单击在3个状态之间切换(选中|中间|未选中)(checked|intermediate|unchecked).。
自定义属性:
{ sorter: "number", // 对数字使用sorteruses sorter for numbers
align: "center" // 居中文本对齐center text alignment
autosearch: true // 当用户单击筛选器中的复选框时触发搜索triggers searching when the user clicks checkbox in filter
}
textarea
Textarea字段在插入和编辑行中呈现<Textarea>,在筛选器行中呈现<input type=“text”>。
自定义属性:
{
autosearch: true, // 当用户在筛选器输入中按“回车”键时触发搜索 triggers searching when the user presses `enter` key in the filter input
readOnly: false // 布尔值定义复选框是否为只读(在v1.4中添加)a boolean defines whether checkbox is readonly (added in v1.4)
}
control
控制字段在数据行中呈现删除和编辑按钮,在过滤器中搜索和添加按钮,并相应地插入行。它还呈现在标题行中过滤和搜索之间的按钮切换。
自定义属性:
{
editButton: true, // show edit button
deleteButton: true, // show delete button
clearFilterButton: true, // show clear filter button
modeSwitchButton: true, // show switching filtering/inserting button
align: "center", // center content alignment
width: 50, // default column width is 50px
filtering: false, // disable filtering for column
inserting: false, // disable inserting for column
editing: false, // disable editing for column
sorting: false, // disable sorting for column
searchModeButtonTooltip: "Switch to searching", // tooltip of switching filtering/inserting button in inserting mode
insertModeButtonTooltip: "Switch to inserting", // tooltip of switching filtering/inserting button in filtering mode
editButtonTooltip: "Edit", // tooltip of edit item button
deleteButtonTooltip: "Delete", // tooltip of delete item button
searchButtonTooltip: "Search", // tooltip of search button
clearFilterButtonTooltip: "Clear filter", // tooltip of clear filter button
insertButtonTooltip: "Insert", // tooltip of insert button
updateButtonTooltip: "Update", // tooltip of update item button
cancelEditButtonTooltip: "Cancel edit", // tooltip of cancel editing button
}
Custom Field
如果需要完全自定义的字段,则对象jsGrid.fields很容易扩展。
在本例中,我们定义了新的网格字段date:
date
:
var MyDateField = function(config) {
jsGrid.Field.call(this, config);
};
MyDateField.prototype = new jsGrid.Field({
css: "date-field", // redefine general property 'css'
align: "center", // redefine general property 'align'
myCustomProperty: "foo", // custom property
sorter: function(date1, date2) {
return new Date(date1) - new Date(date2);
},
itemTemplate: function(value) {
return new Date(value).toDateString();
},
insertTemplate: function(value) {
return this._insertPicker = $("<input>").datepicker({ defaultDate: new Date() });
},
editTemplate: function(value) {
return this._editPicker = $("<input>").datepicker().datepicker("setDate", new Date(value));
},
insertValue: function() {
return this._insertPicker.datepicker("getDate").toISOString();
},
editValue: function() {
return this._editPicker.datepicker("getDate").toISOString();
}
});
jsGrid.fields.date = MyDateField;
若要拥有所有常规网格字段属性,自定义字段类应继承jsGrid.Field类或任何其他字段类。在这里itemTemplate只返回日期的字符串表示形式,insertTemplate和editTemplate创建用于插入和编辑行的jqueryui日期选择器。当然,应该包含jQueryUI库才能使其正常工作。insertValue和editValue返回日期以相应地 insertValue
和editValue
。我们还定义了日期特定的分类器。
现在,我们的新字段日期可以在网格配置中使用,如下所示:
{
fields: [
...
{ type: "date", myCustomProperty: "bar" },
...
]
}
Methods
jsGrid 可以直接称为jsGrid 或 jQuery plugin方法。
要使用jsGrid插件调用方法,只需使用方法名称和所需参数作为下一个参数来调用jsGrid:
// 使用jQuery插件调用方法calling method with jQuery plugin
$("#grid").jsGrid("methodName", param1, param2);
要直接调用方法,您需要检索网格实例或使用构造函数创建grid
// 从元素数据检索grid实例retrieve grid instance from element datavar grid = $("#grid").data("JSGrid"); // 使用构造函数创建grid create grid with the constructorvar grid = new jsGrid.Grid($("#grid"), { ... }); // 直接调用方法call method directly
grid.methodName(param1, param2);
cancelEdit()
取消行编辑。
$("#grid").jsGrid("cancelEdit");
clearFilter(): Promise
清除当前筛选器并使用空筛选器执行搜索。当数据筛选完成时返回jQuery promise resolved。
$("#grid").jsGrid("clearFilter").done(function() {
console.log("filtering completed");
});
clearInsert()
清除当前插入行。
$("#grid").jsGrid("clearInsert");
deleteItem(item|$row|rowNode): Promise
从grid中删除指定的行。在删除完成时返回jQuery promise resolved。
item|$row|rowNode是对项或行jQueryElement或行DomNode的引用。
// delete row by item reference
$("#grid").jsGrid("deleteItem", item);
// delete row by jQueryElement
$("#grid").jsGrid("deleteItem", $(".specific-row"));
// delete row by DomNode
$("#grid").jsGrid("deleteItem", rowNode);
destroy()
破坏grid并使节点恢复其原始状态。
$("#grid").jsGrid("destroy");
editItem(item|$row|rowNode)
设置grid编辑行。
item|$row|rowNode是对项或行jQueryElement或行DomNode的引用。
// edit row by item reference
$("#grid").jsGrid("editItem", item);
// edit row by jQueryElement
$("#grid").jsGrid("editItem", $(".specific-row"));
// edit row by DomNode
$("#grid").jsGrid("editItem", rowNode);
getFilter(): Object
获取网格过滤器作为普通对象。
var filter = $("#grid").jsGrid("getFilter");
getSorting(): Object
version added: 1.2
使用以下格式将grid当前排序参数作为纯对象获取:
{ field, // 网格排序所依据的字段的名称the name of the field by which grid is sorted
order // “asc”或“desc”,取决于排序顺序'asc' or 'desc' depending on sort order
}
var sorting = $("#grid").jsGrid("getSorting");
fieldOption(fieldName|fieldIndex, optionName, [optionValue])
version added: 1.3
获取或设置字段选项的值
fieldName或fieldIndex是获取/设置选项值的字段的名称或索引(如果grid包含多个同名字段,则将使用第一个字段)。
optionName 是字段选项的名称。
optionValue 是要设置的新选项值。
如果未指定optionValue,则将返回字段optionName的值。
// 隐藏字段“ClientName”
$("#grid").jsGrid("fieldOption", "ClientName", "visible", false);
// 获取第二个字段的宽度
var secondFieldOption = $("#grid").jsGrid("fieldOption", 1, "width");
insertItem([item]): Promise
基于项在网格中插入行。在插入完成时返回jQuery promise解析。
item是要传递到的项控制器.插入项.
如果未指定item,则插入行的数据将被插入。
// insert item from inserting row 新建到插入行
$("#grid").jsGrid("insertItem"); // insert item 插入项目 $("#grid").jsGrid("insertItem", { Name: "John", Age: 25, Country: 2 }).done(function() { console.log("insertion completed"); });
loadData([filter]): Promise
加载相应的数据调用controller.loadData
方法。当数据加载完成时返回jQuery promise解析。与 search
方法不同,它保留当前的排序和分页。
filter 是要传递到的 controller.loadData
.
如果未指定过滤器,将应用当前过滤器(过滤行值)。
// loadData with current grid filter
$("#grid").jsGrid("loadData");
// loadData with custom filter
$("#grid").jsGrid("loadData", { Name: "John" }).done(function() {
console.log("data loaded");
});
openPage(pageIndex)
打开指定索引的页面。
pageIndex是要打开的页面的基于索引的索引。[1]应在总页数之间。
option(optionName, [optionValue])
获取或设置选项的值。
optionName是选项的名称。
optionValue是要设置的新选项值。
如果未指定optionValue,则将返回optionName的值。
// turn off paging
$("#grid").jsGrid("option", "paging", false);
// get current page index
var pageIndex = $("#grid").jsGrid("option", "pageIndex");
refresh()
刷新网格。呈现grid内容和pager内容,重新计算大小。
$("#grid").jsGrid("refresh");
render(): Promise
执行完整的栅格渲染。如果选项autoload为true,则调用 controller.loadData
. grid 的状态(如当前页和排序)将保留。当数据加载完成时返回jQuery promise解析。如果自动加载被禁用,承诺立即得到解决。
$("#grid").jsGrid("render").done(function() {
console.log("rendering completed and data loaded");
});
reset()
重置grid的状态。转到第一个页数据,重置排序,然后调用刷新。
$("#grid").jsGrid("reset");
rowByItem(item): jQueryElement
version added: 1.3
获取与项对应的行jQuery元素。
item是与行对应的项。
var $row = $("#grid").jsGrid("rowByItem", item);
search([filter]): Promise
执行grid过滤。当数据加载完成时返回jQuery promise解析。与loadData方法不同,它重置当前的排序和分页。
筛选器是要传递到的筛选器controller.loadData
如果未指定过滤器,将应用当前过滤器(过滤行值)。
// search with current grid filter
$("#grid").jsGrid("search");
// search with custom filter
$("#grid").jsGrid("search", { Name: "John" }).done(function() {
console.log("filtering completed");
});
showPrevPages()
pageButtonCount时显示上一组页面。
$("#grid").jsGrid("showPrevPages");
showNextPages()
pageButtonCount时显示下一组页面
$("#grid").jsGrid("showNextPages");
sort(sortConfig|field, [order]): Promise
按指定字段对grid排序。返回排序完成时解析的jQuery promise。
sortConfig是以下结构{field:(fieldIndex | fieldName | field),顺序:(“asc”|“desc”)}
field 是要排序的字段。它可以是从零开始的字段索引、字段名或字段引用
order is the sorting order. Accepts the following values: “asc” order是排序顺序。接受以下值:“asc” | “desc” |
如果未指定顺序,则当grid已按同一字段排序时,数据将按与当前相反的顺序排序。或“asc”表示按其他字段排序。
当grid数据由页面加载时(pageLoading为true)排序调用 controller.loadData
带有排序参数。在网格控制器部分阅读更多. 链接 Grid Controller
// sorting grid by first field
$("#grid").jsGrid("sort", 0);
// sorting grid by field "Name" in descending order
$("#grid").jsGrid("sort", { field: "Name", order: "desc" });
// sorting grid by myField in ascending order
$("#grid").jsGrid("sort", myField, "asc").done(function() {
console.log("sorting completed");
});
updateItem([item|$row|rowNode], [editedItem]): Promise
更新网格的项和行。在更新完成时返回jQuery promise resolved。
item |$row | rowNode是对项目或行jQueryElement或行DomNode的引用。
editEditItem是要传递到controller.updateItem
.
如果未指定item |$row | rowNode,则编辑行将被更新。
如果未指定editItem,则将从编辑行获取数据。
// update currently editing row
$("#grid").jsGrid("updateItem");
// update currently editing row with specified data
$("#grid").jsGrid("updateItem", { ID: 1, Name: "John", Age: 25, Country: 2 });
// update specified item with particular data (row DomNode or row jQueryElement can be used instead of item reference)
$("#grid").jsGrid("updateItem", item, { ID: 1, Name: "John", Age: 25, Country: 2 }).done(function() {
console.log("update completed");
});
jsGrid.locale(localeName|localeConfig)
version added: 1.4
设置所有网格的当前区域设置。
localeName | localeConfig是支持的语言环境的名称(请参阅可用的语言环境或自定义本地化配置)。在本地化中查找有关自定义本地化配置的详细信息。
链接 Localization.
// set French locale
jsGrid.locale("fr");
jsGrid.setDefaults(config)
为所有grid设置默认选项。
jsGrid.setDefaults({
filtering: true,
inserting: true
});
jsGrid.setDefaults(fieldName, config)
设置特定字段的默认选项。
jsGrid.setDefaults("text", {
width: 150,
css: "text-field-cls"
});
Callbacks
jsGrid允许指定要对特定事件执行的回调函数。
支持以下回调:
{
onDataLoading: function(args) {}, // before controller.loadData
onDataLoaded: function(args) {}, // on done of controller.loadData
onError: function(args) {}, // on fail of any controller call
onInit: function(args) {}, // after grid initialization
onItemInserting: function(args) {}, // before controller.insertItem
onItemInserted: function(args) {}, // on done of controller.insertItem
onItemUpdating: function(args) {}, // before controller.updateItem
onItemUpdated: function(args) {}, // on done of controller.updateItem
onItemDeleting: function(args) {}, // before controller.deleteItem
onItemDeleted: function(args) {}, // on done of controller.deleteItem
onItemInvalid: function(args) {}, // after item validation, in case data is invalid
onOptionChanging: function(args) {}, // before changing the grid option
onOptionChanged: function(args) {}, // after changing the grid option
onPageChanged: function(args) {}, // after changing the current page
onRefreshing: function(args) {}, // before grid refresh
onRefreshed: function(args) {}, // after grid refresh
}
onDataLoading
在加载数据之前激发。
具有以下参数:
{
grid // grid instance
filter // loading filter object
}
取消数据加载
version added: 1.2
取消数据加载集参数取消=正确。
在以下示例中,当筛选器的“name”字段为空时,将取消加载:
$("#grid").jsGrid({
...
onDataLoading: function(args) {
// cancel loading data if 'name' is empty
if(args.filter.name === "") {
args.cancel = true;
}
}
});
onDataLoaded
加载数据后激发。
具有以下参数:
{
grid // grid instance
data // load result (array of items or data structure for loading by page scenario)
}
onInit
version added: 1.5
在grid初始化后在渲染之前激发。通常用于获取grid实例。
具有以下参数:
{
grid // grid instance
}
In the following example we get the grid instance on initialization:
var gridInstance;
$("#grid").jsGrid({
...
onInit: function(args) {
gridInstance = args.grid;
}
});
onError
当控制器处理程序承诺失败时激发。
具有以下参数:
{
grid // grid instance
args // an array of arguments provided to fail promise handler
}
onItemDeleting
在删除项之前激发。
具有以下参数:
{
grid // grid instance
row // deleting row jQuery element
item // deleting item
itemIndex // deleting item index
}
Cancel Item Deletion
version added: 1.2
取消项目删除集参数取消=正确。这允许在执行实际删除之前进行验证。
在以下示例中,将取消删除标记为受保护的项:
$("#grid").jsGrid({
...
onItemDeleting: function(args) {
// cancel deletion of the item with 'protected' field
if(args.item.protected) {
args.cancel = true;
}
}
});
onItemDeleted
在项删除后激发。
具有以下参数:
{
grid // grid instance
row // deleted row jQuery element
item // deleted item
itemIndex // deleted item index
}
onItemEditing
version added: 1.4
在编辑项之前激发。
具有以下参数:
{
grid // grid instance
row // editing row jQuery element
item // editing item
itemIndex // editing item index
}
取消项目编辑
取消项目编辑 args.cancel = true
. 。这允许防止有条件地编辑行。
在以下示例中,取消了对“ID”=0的项的行的编辑:
$("#grid").jsGrid({
...
onItemEditing: function(args) {
// cancel editing of the row of item with field 'ID' = 0
if(args.item.ID === 0) {
args.cancel = true;
}
}
});
onItemInserting
在插入项之前激发。
具有以下参数:
{
grid // grid instance
item // inserting item
}
取消项目插入
version added: 1.2
取消项目插入args.cancel = true
.。这允许在执行实际插入之前进行验证。
在以下示例中,允许插入指定了“name”的项:
$("#grid").jsGrid({
...
onItemInserting: function(args) {
// cancel insertion of the item with empty 'name' field
if(args.item.name === "") {
args.cancel = true;
alert("Specify the name of the item!");
}
}
});
onItemInserted
在项插入后激发。
具有以下参数:
{
grid // grid instance
item // inserted item
}
onItemInvalid
当项不遵循插入或更新的验证规则时激发。
具有以下参数:
{
grid // grid instance
row // inserting/editing row jQuery element
item // inserting/editing item
itemIndex // inserting/editing item index
errors // array of validation violations in format { field: "fieldName", message: "validator message" }
}
以下处理程序在控制台上打印错误
$("#grid").jsGrid({
...
onItemInvalid: function(args) {
// prints [{ field: "Name", message: "Enter client name" }]
console.log(args.errors);
}
});
onItemUpdating
在项更新之前激发。
具有以下参数:
{
grid // grid instance
row // updating row jQuery element
item // updating item
itemIndex // updating item index
previousItem // shallow copy (not deep copy) of item before editing
}
取消项目更新
version added: 1.2
取消项目更新 args.cancel = true
.。这允许在执行实际更新之前进行验证。
在以下示例中,允许使用指定的“name”更新项:
$("#grid").jsGrid({
...
onItemUpdating: function(args) {
// cancel update of the item with empty 'name' field
if(args.item.name === "") {
args.cancel = true;
alert("Specify the name of the item!");
}
}
});
onItemUpdated
在项更新后激发。
具有以下参数:
{
grid // grid instance
row // updated row jQuery element
item // updated item
itemIndex // updated item index
previousItem // shallow copy (not deep copy) of item before editing
}
onOptionChanging
Fires before grid option value change.
Has the following arguments:
{
grid // grid instance
option // name of option to be changed
oldValue // old value of option
newValue // new value of option
}
onOptionChanged
在grid选项值更改后激发。
具有以下参数:
{
grid // grid instance
option // name of changed option
value // changed option value
}
onPageChanged
version added: 1.5
当grid当前页索引改变时触发。它可以通过在带有页导航链接的页面之间切换,或者调用方法openPage,或者更改选项pageIndex来实现。
具有以下参数:
{
grid // grid instance
pageIndex // current page index
}
在下面的例子中,我们在浏览器控制台中打印当前页面索引,一旦它被改变:
$("#grid").jsGrid({
...
onPageChanged: function(args) {
console.log(args.pageIndex);
}
});
onRefreshing
在grid刷新之前触发。
具有以下参数:
{
grid // grid instance
}
onRefreshed
在grid刷新后激发。
具有以下参数:
{
grid // grid instance
}
Grid Controller
控制器是grid和数据存储之间的网关。所有的数据操作都调用一致的控制器方法。默认情况下,grid有一个空的控制器,可以处理存储在选项数据中的静态项数组。
控制器应实现以下方法:
{
loadData: function(filter) { ... },
insertItem: function(item) { ... },
updateItem: function(item) { ... },
deleteItem: function(item) { ... }
}
异步控制器方法应该返回一个承诺,在请求完成后解析。从v1.5开始,jsGrid就支持标准的JavaScript Promise/A,早期的版本只支持query .Promise。
例如,典型REST服务的控制器可能看起来像:
{
loadData: function(filter) {
return $.ajax({
type: "GET",
url: "/items",
data: filter
});
},
insertItem: function(item) {
return $.ajax({
type: "POST",
url: "/items",
data: item
});
},
updateItem: function(item) {
return $.ajax({
type: "PUT",
url: "/items",
data: item
});
},
deleteItem: function(item) {
return $.ajax({
type: "DELETE",
url: "/items",
data: item
});
},
}
loadData(filter): Promise|dataResult
调用数据加载。
filter 包含启用过滤的字段的所有过滤器参数
当页面pageLoading
为 true
且数据由页面加载时,filter还包括两个参数:
{
pageIndex // current page index
pageSize // the size of page
}
当grid排序启用,过滤器包括两个更多的参数:
{
sortField // the name of sorting field
sortOrder // the order of sorting as string "asc"|"desc"
}
方法应该返回 dataResult
或将用 dataResult
解决的jQuery承诺。
dataResult 依赖于 pageLoading
。当pageLoading
为 false
(默认情况下)时,数据结果是一个纯javascript对象数组。如果pageLoading
是true
的,数据结果应该具有以下结构
{
data // array of items
itemsCount // total items amount in storage
}
insertItem(item): Promise|insertedItem
项是要插入的项。
方法应返回 insertedItem
或 jQuery promise,后者将由 insertedItem
解析。如果没有返回项,则插入项将用作插入项。
updateItem(item): Promise|updatedItem
在项目更新时调用。
方法应返回updatedItem或jQuery promise,后者将使用updatedItem进行解析。如果没有返回项,则更新项将用作更新项。
item是要更新的项。
deleteItem(item): Promise
在项目删除时调用。
若删除是异步的,则该方法应返回jQuery promise,当删除完成时将解析该承诺。
item是要删除的项。
Validation
version added: 1.4
Field Validation Config
字段的validate选项可以有4种不同的值类型 string|Object|Array|function
:
validate: "validatorName"
validatorName -是中验证程序的字符串键j sGrid.validators 登记。注册表可以很容易地扩展。在这里查看可用的内置验证器。链接 built-in validators here.
在以下示例中,将应用所需的验证器:
$("#grid").jsGrid({
...
fields: [{ type: "text", name: "FieldName", validate: "required" }]
});
validate: validationConfig
validateConfig -是一个简单的对象,结构如下:
{
validator: string|function(value, item, param), // 内置验证器名称或自定义验证函数built-in validator name or custom validation function
message: string|function, // 验证message 或function(value, item) 返回验证消息validation message or a function(value, item) returning validation message
param: any // 一个普通的对象,带有要传递给验证函数的参数a plain object with parameters to be passed to validation function
}
在下面的例子中,range
验证器应用自定义验证消息和参数中提供的范围:
$("#grid").jsGrid({
...
fields: [{
type: "number",
name: "Age",
validate: {
validator: "range",
message: function(value, item) {
return "The client age should be between 21 and 80. Entered age is \"" + value + "\" is out of specified range.";
},
param: [21, 80]
}
}]
});
validate: validateArray
validateArray—是一个验证器数组。它可以包含
string
- validator nameObject
- validator configuration of structure{ validator, message, param }
function
- validation function asfunction(value, item)
在下面的例子中,字段有三个验证器:required, range和一个自定义 function 验证器:
$("#grid").jsGrid({
...
fields: [{
type: "number",
name: "Age",
validate: [
"required",
{ validator: "range", param: [21, 80] },
function(value, item) {
return item.IsRetired ? value > 55 : true;
}
]
}]
});
validate: function(value, item, param)
函数的参数:
value
- entered value of the fielditem
- editing/inserting itemparam
- a parameter provided by validator (applicable only when validation config is defined at validation object or an array of objects)
在下面的例子中,字段具有自定义验证功能:
$("#grid").jsGrid({
...
fields: [{
type: "text",
name: "Phone",
validate: function(value, item) {
return value.length == 10 && phoneBelongsToCountry(value, item.Country);
}
}]
});
Built-in Validators
在jsGrid.validators对象包含所有内置验证器。哈希的键是验证器名称,值是验证器配置。
jsGrid.validators包含以下内置验证器:
- required - the field value is required
- rangeLength - the length of the field value is limited by range (the range should be provided as an array in
param
field of validation config) - minLength - the minimum length of the field value is limited (the minimum value should be provided in
param
field of validation config) - maxLength - the maximum length of the field value is limited (the maximum value should be provided in
param
field of validation config) - pattern - the field value should match the defined pattern (the pattern should be provided as a string regexp in
param
field of validation config) - range - the value of the number field is limited by range (the range should be provided as an array in
param
field of validation config) - min - the minimum value of the number field is limited (the minimum should be provided in
param
field of validation config) - max - the maximum value of the number field is limited (the maximum should be provided in
param
field of validation config)
Custom Validators
要定义自定义验证器,只需将其添加到jsGrid.validators对象。
在以下示例中,注册了自定义验证器 time
:
jsGrid.validators.time = {
message: "Please enter a valid time, between 00:00 and 23:59",
validator: function(value, item) {
return /^([01]\d|2[0-3]|[0-9])(:[0-5]\d){1,2}$/.test(value);
}
}
Localization
version added: 1.4
可以使用为页面上的所有网格设置当前区域设置jsGrid.locale(localeName)方法。 链接 jsGrid.locale(localeName)
可以将新的自定义区域设置添加到 jsGrid.locales 如下:
jsGrid.locales.my_lang = {
// localization config goes here
...
};
下面是西班牙语的本地化配置 i18n/es.js.
查找所有可用的区域设置 here.
Sorting Strategies
所有支持的排序策略都存储在 jsGrid.sortStrategies 对象,其中 key 是策略的名称,值是 sortingFunction。
jsGrid.sortStrategies 包含以下内置排序策略:
{
string: { ... }, // string sorter
number: { ... }, // number sorter
date: { ... }, // date sorter
numberAsString: { ... } // numbers are parsed before comparison
}
sortingFunction 是具有以下格式的排序函数:
function(value1, value2) {
if(value1 < value2) return -1; // return negative value when first is less than second
if(value1 === value2) return 0; // return zero if values are equal
if(value1 > value2) return 1; // return positive value when first is greater than second
}
Custom Sorting Strategy
如果需要自定义排序策略,则 jsGrid.sortStrategies 很容易扩展。
在本例中,我们为客户机对象定义了新的排序策略:
// clients array
var clients = [{
Index: 1,
Name: "John",
Age: 25
}, ...];
// sort clients by name and then by age
jsGrid.sortStrategies.client = function(index1, index2) {
var client1 = clients[index1];
var client2 = clients[index2];
return client1.Name.localeCompare(client2.Name)
|| client1.Age - client2.Age;
};
现在,我们新的排序策略client
可以在grid 配置中使用,如下所示:
{
fields: [
...
{ name: "Index", sorter: "client" },
...
]
}
值得一提的是,如果您只需要一次特定的排序,您可以只在 sorter 中内联排序功能而不注册新策略:
{
fields: [
...
{
name: "Index",
sorter: function(index1, index2) {
var client1 = clients[index1];
var client2 = clients[index2];
return client1.Name.localeCompare(client2.Name)
|| client1.Age - client2.Age;
}
},
...
]
}
Load Strategies
grid关于数据源交互的行为由负载策略定义。
加载策略有以下方法:
{
firstDisplayIndex: function() {}, // returns the index of the first displayed item
lastDisplayIndex: function() {}, // returns the index of the last displayed item
itemsCount: function() {}, // returns the total amount of grid items
openPage: function(index) {}, // handles opening of the particular page
loadParams: function() {}, // returns additional parameters for controller.loadData method
sort: function() {}, // handles sorting of data in the grid, should return a Promise
reset: function() {}, // handles grid refresh on grid reset with 'reset' method call, should return a Promise
finishLoad: function(loadedData) {}, // handles the finish of loading data by controller.loadData
finishInsert: function(insertedItem) {}, // handles the finish of inserting item by controller.insertItem
finishDelete: function(deletedItem, deletedItemIndex) {} // handles the finish of deleting item by controller.deleteItem
}
有两种内置加载策略:DirectLoadingStrategy(对于pageLoading=false
)和PageLoadingStrategy(对于pageLoading=true
)。
DirectLoadingStrategy
当页面加载被关闭时使用 DirectLoadingStrategy (pageLoading=false)。
它提供以下行为:
firstDisplayIndex返回显示页面上第一项的索引
lastDisplayIndex返回显示页面上最后一项的索引
itemsCount返回所有加载项的实际数量
openPage刷新grid以呈现当前页面的项
loadParams返回空对象,因为不需要额外的加载参数
sort对数据项进行排序,并调用grid.refresh刷新grid
reset 调用网格。方法刷新grid
finishLoad放置来自控制器的数据。将数据加载到grid的选项数据中
finishInsert将新插入的项推入选项数据并刷新grid
finishDelete从选项数据中删除并重置grid
PageLoadingStrategy
PageLoadingStrategy在数据按页加载到grid时使用(pageLoading=true)。
它提供以下行为:
firstDisplayIndex返回0,因为所有加载的项都显示在当前页上
lastDisplayIndex返回自页加载数据以来已加载项的数量
itemsCount返回itemsCount由提供controller.loadData
(请参阅第节控controller.loadData)
openPage调用grid
.loadData
为当前页加载数据
loadParams返回一个结构为{pageIndex,pageSize}的对象,以向服务器提供分页信息
sort 呼叫grid.loadData
从服务器加载排序的数据
finishLoad保存服务器返回的itemsCount并将数据放入网格的选项数据中
reset 呼叫grid.loadData
方法刷新数据
finishInsert 调用grid
.搜索重新加载数据
finishDelete 调用grid
.搜索重新加载数据
Custom LoadStrategy
loadStrategy
选项允许指定一个自定义加载策略来定制grid的行为。最简单的方法就是继承现有的策略。
默认情况下,DirectLoadingStrategy在删除项目时重置grid (重置分页和排序)。以下示例显示如何创建自定义策略,以避免在删除项时grid 网格。
var MyCustomDirectLoadStrategy = function(grid) {
jsGrid.loadStrategies.DirectLoadingStrategy.call(this, grid);
};
MyCustomDirectLoadStrategy.prototype = new jsGrid.loadStrategies.DirectLoadingStrategy();
MyCustomDirectLoadStrategy.prototype.finishDelete = function(deletedItem, deletedItemIndex) {
var grid = this._grid;
grid.option("data").splice(deletedItemIndex, 1);
grid.refresh();
};
// use custom strategy in grid config
$("#grid").jsGrid({
loadStrategy: function() {
return new MyCustomDirectLoadStrategy(this);
},
...
});
Load Indication
默认情况下,jsGrid使用 jsGrid.LoadIndicator. 可以使用loadIndicator选项自定义负载指示器。设置返回支持以下接口的对象或函数:
{
show: function() { ... } // called on loading start
hide: function() { ... } // called on loading finish
}
这个简单的示例将消息打印到控制台,而不是显示负载指示器:
{
loadIndicator: {
show: function() {
console.log("loading started");
},
hide: function() {
console.log("loading finished");
}
}
}
如果 loadIndicator
是一个函数,它接受以下格式的load indicator配置:
{
container, // grid container div
message, // the loading message is a value of the option loadMessage
shading // the boolean value defining whether to show shading. This is a value of the option loadShading
}
将消息打印到控制台的类似示例显示了如何使用返回对象的函数配置加载指示器:
{
loadIndicator: function(config) {
return {
show: function() {
console.log("loading started: " + config.message);
},
hide: function() {
console.log("loading finished");
}
};
}
}
当您想要使用页面上所有其他ajax请求所使用的任何外部加载指示器时,定制加载指示器非常有用。
这个例子展示了如何使用spin.js 表示装载:
{
loadIndicator: function(config) {
var container = config.container[0];
var spinner = new Spinner();
return {
show: function() {
spinner.spin(container);
},
hide: function() {
spinner.stop();
}
};
}
}
Requirement
jQuery版本1.8.3或更高版本。
Compatibility
Desktop
- Chrome
- Safari
- Firefox
- Opera 15+
- IE 8+
Mobile
- Safari for iOS
- Chrome for Android
- IE10 for WP8