Skip to content

Instantly share code, notes, and snippets.

@devoto13
Last active August 29, 2015 14:17
Show Gist options
  • Save devoto13/fdbe3309b1a19e59ef92 to your computer and use it in GitHub Desktop.
Save devoto13/fdbe3309b1a19e59ef92 to your computer and use it in GitHub Desktop.
table.js
/*
* Library for working with db tables.
*
* Config options:
*
* container string: идентификатор контейнера для таблицы
* hasInsertButton bool: показывать ли кнопку добавления записи
* insertButtonText string: текст кнопки добавления
* enableSorting bool: включить сортировку
* hightlightOddRows bool: подсвечивать четные строки другим цветом
* showOperations bool: показывать ли операции редактирвоания и удаления
*
* table параметры для выборки
* -.name string: таблицa из которой производится выборка
* -.visibleFields Array(string): отображаемые поля
* -.editableFields Array(string): редактируемые поля
* -.insertableFields Array(string): поля в форме добавления записи
* -.showCaption bool: отображать ли заголовок таблицы
* -.primaryKey string: название первичного ключа таблицы
*
* templates шаблоны для вывода
* -.table string: шаблон всей таблицы
* -.formItem string: шаблон для вывода формы редактирования
*
* buttons селекторы для кнопок
* -.edit string: для кнопки редактирования
* -.delete string: для кнопки удаления
* -.insert string: для кнопки добавления
*
*/
var Table = {
Init: function(config) {
this.setDefaultConfig(config);
this.parseConfig(config);
this.queryObjects()
this.setupTemplates();
this.bindEvents();
this.eventListeners = Array();
},
setDefaultConfig: function () {
this.parseConfig({
insertButtonText: 'Insert a record',
hasInsertButton: false,
buttons: {
edit: '.edit-button',
delete: '.delete-button',
insert: '.insert-button'
},
templates: {
table: $('#table-template').html(),
formItem: $('#form-item-template').html()
},
table: {
showCaption: false
},
enableSorting: false,
enableFiltering: false,
highlightOddRows: false,
showOperations: true,
dialog: '#dialog',
locker: '#locker'
});
},
parseConfig: function (config) {
var self = Table;
$.each(config, function (key, value) {
if (config.hasOwnProperty(key))
if (typeof config[key] == "object") {
if (typeof self[key] != 'object') self[key] = {};
$.each(config[key], function (inskey, insvalue) {
self[key][inskey] = insvalue;
});
}
else
self[key] = value;
});
},
queryObjects: function() {
this.container = $(this.container);
this.dialog = $(this.dialog);
this.locker = $(this.locker);
},
setupTemplates: function() {
var self = Table;
this.templates.table = Handlebars.compile(this.templates.table);
this.templates.rows = Handlebars.compile(this.templates.rows);
this.templates.formItem = Handlebars.compile(this.templates.formItem);
Handlebars.registerHelper('ucfirst', function (str) {
return ucfirst(str);
});
Handlebars.registerHelper('inc', function (str) {
return ++str;
});
Handlebars.registerHelper('heading_field', function (str) {
var value = str.replace(/_/g, ' ');
value = value.replace('id', 'ID');
var array = value.split(' ');
$.each(array, function (key, value) {
array[key] = ucfirst(value);
});
value = array.join(' ');
return value;
});
Handlebars.registerHelper('table_row', function (heading, array, operations) {
var row = operations ? '<td class="edit-cell"><img data-type="edit" class="edit-button edit-tools"'
+ ' src="/img/edit.gif"><img data-type="delete" class="delete-button'
+ ' edit-tools" src="/img/delete1.png"></td>' : '';
$.each(array, function (key, value) {
if (heading.indexOf(key) + 1)
row += '<td class="col' + key + '">' + value + '</td>';
});
return new Handlebars.SafeString(row);
});
Handlebars.registerHelper('query_row', function (array) {
var row = '';
$.each(array, function (key, value) {
row += '<td>' + value + '</td>';
});
return new Handlebars.SafeString(row);
});
Handlebars.isOdd = false;
Handlebars.registerHelper('is_odd', function () {
var value = (Handlebars.isOdd) ? ' class="odd-row"' : '';
Handlebars.isOdd = !Handlebars.isOdd;
return new Handlebars.SafeString(value);
});
Handlebars.registerHelper('get_id', function (array) {
return array[self.table.primaryKey];
});
},
bindButtonEvents: function () {
var self = Table;
$.each(self.buttons, function (key, value) {
$(self.buttons[key]).on('click', self['create' + ucfirst(key) + 'Form']);
});
},
bindEvents: function () {
this.dialog
.children().filter('#dialog-buttons')
.children().filter('#dialog-cancel')
.on('click', this.hideForm);
},
LoadData: function () {
var self = Table;
$.getJSON('/tables/getdata', {
table: self.table.name,
},
function (data) {
data.hasInsertButton = self.hasInsertButton;
data.showCaption = self.table.showCaption;
data.heading = self.table.visibleFields;
data.enableSorting = self.enableSorting;
data.enableFiltering = self.enableFiltering;
data.highlightOddRows = self.highlightOddRows;
data.insertButtonText = self.insertButtonText;
data.operations = self.showOperations;
self.container.html(self.templates.table(data));
self.bindButtonEvents();
resize();
$.each(self.eventListeners, function (key, value) {
value();
});
});
},
onDataLoad: function (func) {
var self = Table;
self.eventListeners.push(func);
},
sendForm: function (e) {
e.preventDefault();
var self = Table,
form = self.dialog.find('form');
$.ajax({
url: 'tables/' + form.attr('action'),
type: 'POST',
data: form.serialize(),
success: function (data) {
self.LoadData();
self.hideForm();
}
});
},
createInsertForm: function () {
var heading = Table.getHeading('insert'),
data = Table.createForm('insert', null, heading);
},
createEditForm: function () {
var heading = Table.getHeading('edit'),
id = $(this).parent().parent().attr('id').substr(3);
data = Table.createForm('edit', id, heading);
},
createDeleteForm: function () {
var heading = Table.getHeading('delete'),
id = $(this).parent().parent().attr('id').substr(3),
data = Table.createForm('delete', id, heading);
},
getHeading: function (type) {
var self = Table;
return self.table[type + 'ableFields'];
},
createForm: function (type, id, heading) {
var self = Table,
data = {
type: type,
id: id != null ? id : '',
primaryKey: self.table.primaryKey,
table: self.table.name,
fields: []
};
if (data.type != 'delete')
$.each(heading, function (key, value) {
data.fields.push({
name: value,
data: self.getContent(id, value)
});
});
$('#dialog-content').html(self.templates.formItem(data));
$('#dialog-title').html(ucfirst(type) + ' a record'
+ (data.type != 'insert' ? ' #' + data.id : ''));
$('#dialog-submit')
.html(ucfirst(data.type))
.unbind('click')
.on('click', self.sendForm);
self.showForm(data.type);
},
getContent: function (id, field) {
return id != null ? $('#row' + id + ' .col' + field).html() : '';
},
showForm: function (type) {
var self = Table;
var left = (($(window).width() - self.dialog.width()) / 2),
top = (($(window).height() - self.dialog.height()) / 2) - 100;
self.locker.show();
self.dialog.show().css({
left: left,
top: top
});
},
hideForm: function () {
var self = Table;
self.locker.hide();
self.dialog.hide();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment