Building a Web Grid - Part 5
I wanted to have a "pluggable" editor system for the grid so programmers could customize the widgets that appear in the cell when editing begins. This post discusses how to create a custom editor and use it in grijq.
The structure of an editor
An editor for grijq has the following form:
javascript
var myEditor = {
'edit': function(value, options) {
// return a jQuery-wrapped DOM element
// - or-
// return an object like
// {
// element: jQuery-wrapped DOM element,
// afterAppend: function() {
// // run after the DOM element appended
// // to grid cell
// }
// }
},
'unedit': function(input) {
// return value here
}
}You then pass it as an option to the grijq widget when you create it:
javascript
$('#some-table').grijq({editors: {'mytype': myEditor}});And make sure that you've marked the column header with the key of your custom editor:
html
<table id="some-table" width="100">
<colgroup>
<col width="100">
</colgroup>
<thead>
<tr>
<th data-type="mytype">Some value</th>
</tr>
</thead>
<tbody>Or pass in the type to the cols parameter of the grijq widget:
javascript
$('#some-table').grijq({
cols: [{'type': 'mytype'}],
editors: {'mytype': myEditor}
});A custom editor that displays a <select>
I don't have much use for <select>s. However, you may like them. Let's make a custom editor that creates a <select> that contains shirt sizes.
javascript
var shirtSizeEditor = {
'edit': function(value, options) {
var template = '<select>' +
'<option>Large</option>' +
'<option>Medium</option>' +
'<option>Small</option>' +
'</select>';
var select = $(template)
.val(value)
.width('100%')
.keydown(function(e) {
switch(e.keyCode) {
case $.ui.keyCode.UP:
case $.ui.keyCode.DOWN:
e.stopPropagation();
}
});
var wrapper = $('<div></div>').append(select);
return {
element: wrapper,
afterAppend: function() {
select.focus();
}
};
},
'unedit': function(input) {
return input.val();
}
};Now, we'll create a table that uses that.
html
<table id="some-table" width="300">
<colgroup><col width="300"></colgroup>
<thead>
<tr>
<th data-type="shirt-size">Shirt Size</th>
</tr>
</thead>
<tbody>
<tr><td>Large</td></tr>
<tr><td>Medium</td></tr>
<tr><td>Small</td></tr>
<tr><td>WTF?!?!?</td></tr>
</tbody>
</table>Then, we create the grid with grijq.
javascript
$('#some-table').grijq({
width: 316,
editors: {
'shirt-size': shirtSizeEditor
}
});