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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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:

1
$('#some-table').grijq({editors: {'mytype': myEditor}});

And make sure that you’ve marked the column header with the key of your custom editor:

1
2
3
4
5
6
7
8
9
10
<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:

1
2
3
4
$('#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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<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.

1
2
3
4
5
6
$('#some-table').grijq({
width: 316,
editors: {
'shirt-size': shirtSizeEditor
}
});

And you get this handsome devil. It’s a working grid, right there. Click on a cell. Type ‘l’ or ‘m’ or ‘s’. Press ‘F2’. (And, the fact that it doesn’t keep its changed value is by design. The grid isn’t broken. Check out the example simple knockout integration to see how to persist values.)

Shirt Size
Large
Medium
Small
WTF?!?!?