How best to synchronize a YUI DataTable's RecordSet with a JavaScript array?

1.6k views Asked by At

I have a javascript array that I am using as a data source in an editable YUI datatable:

var data = [
    { Col1: "one", Col2: 1 },  
    { Col1: "two", Col2: 2 },      
    { Col1: "three", Col2: 3 },
    { Col1: "four", Col2: 4 }
];
var customFormatter = function (elLiner, oRecord, oColumn, oData) {
    elLiner.innerHTML = "Click me";
    $(elLiner).click(function () {
        var rsvalue = oRecord.getData("Col1");
        var datavalue = data[oRecord.getCount()].Col1;;
        alert("rs:" + rsvalue + ", data:" + datavalue);
    });
};
var coldefs = [
    { key: "Col1", editor: new YAHOO.widget.TextboxCellEditor() },
    { key: "Col2" },
    { key: "Col3", formatter: customFormatter }
];
var datasource = new YAHOO.util.DataSource(data);
datasource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
datasource.responseSchema = { fields: [ "Col1", "Col2" ] };
var datatable = new YAHOO.widget.DataTable("mytable", coldefs, datasource);
datatable.subscribe("cellClickEvent", datatable.onEventShowCellEditor);

When I change a value in the editable cells, I see that the datatable's Record gets updated with the new value, but the underlying data array does not. I would like to work with this javascript array (or another one of this shape) when the user is finished editing the data, where I need to do some post-processing and send it off to the server. In the generally good YUI examples, I don't see that they ever try to reconcile changes made within a datatable to the underlying data source. Does an example like this exist? What is the best way for me to push my changes back into my data array?

Here's a jsfiddle with my little test: http://jsfiddle.net/cfarmerga/uArKs/1/

Should I just catch the editorSaveEvents for the DataTable and just walk the recordset and update my javascript array?

1

There are 1 answers

0
erikaho On BEST ANSWER

If possible, I would suggest rebuilding the array of data once after the user has finished editing, do any post processing, and then send it off to the server. This would be more efficient then trying to keep the datasource and the array in sync after every individual edit. To rebuild the array, you can loop through the datatable's RecordSet.

var rs = datatable.getRecordSet(),
    len = rs.getLength(),
    data = [];

for (var index=0; index < len; index++) {
    data.push(rs.getRecord(index).getData());
}

Note that getData() returns an object representing the entire record. You could also pass individual keys to getData() (such as getData("Col1")) to get individual fields of the record.