80 lines
2.1 KiB
JavaScript
80 lines
2.1 KiB
JavaScript
|
|
"use strict";
|
||
|
|
|
||
|
|
var LinkedTable;
|
||
|
|
|
||
|
|
+function($) {
|
||
|
|
LinkedTable = function(element, options) {
|
||
|
|
this.$element = $(element);
|
||
|
|
this.options = $.extend({}, LinkedTable.DEFAULTS, options);
|
||
|
|
this.clickHandler = function(event) {
|
||
|
|
$(this).addClass('highlight').siblings().removeClass('highlight');
|
||
|
|
};
|
||
|
|
};
|
||
|
|
|
||
|
|
LinkedTable.DEFAULTS = {
|
||
|
|
url: '', //The absolute or relative path to use to query the data. Server is expected to respond with a JSON array of objects.
|
||
|
|
attr: 'data-key-name',
|
||
|
|
selection: 'row' //Currently only row is supported.
|
||
|
|
};
|
||
|
|
|
||
|
|
//TODO
|
||
|
|
LinkedTable.prototype.myMethod = function() {
|
||
|
|
|
||
|
|
};
|
||
|
|
|
||
|
|
//A function that will clean and rebuild the table displaying all the users.
|
||
|
|
LinkedTable.prototype.refresh = function() {
|
||
|
|
var table = this.$element;
|
||
|
|
var thead = table.find("thead tr");
|
||
|
|
var tbody = table.find("tbody");
|
||
|
|
var selection = this.options.selection;
|
||
|
|
var attr = this.options.attr;
|
||
|
|
var clickHandler = this.clickHandler;
|
||
|
|
|
||
|
|
if(thead.length == 0) {
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
//Empty or Create the table body.
|
||
|
|
if(tbody.length != 0) {
|
||
|
|
//Remove the row selection handler.
|
||
|
|
if(selection == 'row') this.$element.off('click', 'tbody tr', clickHandler);
|
||
|
|
//Empty the table of data.
|
||
|
|
tbody.empty();
|
||
|
|
}
|
||
|
|
else {
|
||
|
|
tbody = $("<tbody></tbody>");
|
||
|
|
tbody.appendTo(table);
|
||
|
|
}
|
||
|
|
|
||
|
|
$.getJSON("user-data", function(data) {
|
||
|
|
var headers = thead.children();
|
||
|
|
var attributes = [];
|
||
|
|
|
||
|
|
//Read the table headers to get the data object keys.
|
||
|
|
for(var headerIndex = 0; headerIndex < headers.length; headerIndex++) {
|
||
|
|
var nextHeader = headers[headerIndex];
|
||
|
|
|
||
|
|
attributes[headerIndex] = $(nextHeader).attr(attr);
|
||
|
|
}
|
||
|
|
|
||
|
|
//Add the table data.
|
||
|
|
for(var dataIndex = 0; dataIndex < data.length; dataIndex++) {
|
||
|
|
var rowData = data[dataIndex];
|
||
|
|
var row = $("<tr></tr>");
|
||
|
|
|
||
|
|
row.appendTo(tbody);
|
||
|
|
|
||
|
|
for(var attributeIndex = 0; attributeIndex < attributes.length; attributeIndex++) {
|
||
|
|
var attribute = attributes[attributeIndex];
|
||
|
|
var cellData = rowData[attribute];
|
||
|
|
|
||
|
|
row.append("<td>" + cellData + "</td>");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
//Setup the row selection handler.
|
||
|
|
if(selection == 'row') table.on('click', 'tbody tr', clickHandler);
|
||
|
|
});
|
||
|
|
}
|
||
|
|
}(jQuery);
|