JSFiddle - React, Tailwind, and code Playground
HTML
<table class='updateable'>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
JavaScript
var $j = jQuery.noConflict();
updateableTable.prototype.addRow = function(dataObject) {
//alert('inside add row');
var id = this.getIDFromObject(dataObject);
if (true === this.doesIdExist(id)) {
alert('id ' + id + ' already exists in table.');
return false;
}
//var newRow = $rowTemplate.tmpl(dataObject);
var newRow = this.createPersonRow(dataObject);
this.rowsByID[id] = newRow;
this.dataObjectsByID[id] = dataObject;
this.$tableBody.append(newRow);
return true;
}
updateableTable.prototype.createPersonRow = function(dataObj){
var $tr = $j('<tr id="'+dataObj.ID+'"/>');
var $nameTD = $j('<td>'+dataObj.Name + '</td>');
var $ageTD = $j('<td>'+dataObj.Age+'</td>');
$tr.append($nameTD).append($ageTD);
return $tr[0];
}
updateableTable.prototype.doesIdExist = function(id) {
if (typeof this.rowsByID[id] != 'undefined' &&
typeof this.dataObjectsByID[id] != 'undefined') {
return true;
}
return false;
}
updateableTable.prototype.deleteRow = function(dataObject) {
//alert('inside delete row.');
var id = this.getIDFromObject(dataObject);
if (false === this.doesIdExist(id)) {
alert('id ' + id + ' not in table.');
return false;
}
this.$tableBody.find('#'+id).remove();
delete this.rowsByID[id];
delete this.dataObjectsByID[id];
return true;
}
function updateableTable($table, $rowTemplate, dataObjects, getIDFromObject) // at some point add the ability to add event handlers.
{
this.$rowTemplate = $rowTemplate;
this.$tableBody = $j($table).children('tbody');
this.rowsByID = {};
this.dataObjectsByID = {};
this.getIDFromObject = getIDFromObject;
for(var dataObjKey in dataObjects)
{
this.addRow(dataObjects[dataObjKey]);
}
return this; // still has the protypical methods.
}
var peeps = [{ID:1, Name:'mary', Age:21},{ID:2,Name:'contrary', Age:12}];
var personIDGetter =...