All Downloads are FREE. Search and download functionalities are using the official Maven repository.

butor.js.butor-table.js Maven / Gradle / Ivy

/*
 * Copyright 2013-2018 butor.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * @class $(selector).ButorTable
 * @jquery_plugin mustBeInitilized
 * @description jQuery plugin to make an HTML table scrollable and multi-columns sortable.
 * @param {Map} options - ButorTable options.
 * @param {Boolean} [options.xyz=true] - Flag to allow custom position.
 * @param {Boolean} [options.sortable=false] - Flag to allow sortable colums.
 *
 * @return {jQuerySelector} - jQuerySelector which represents the table structure.
 *
 * @example
 * 
 * 	
 * 		
 * 			
 * 			
 * 		
 * 	
 * 	
 * 		
 * 		
 * 	
 * 	
 * 		
 * 		
 * 	
 * 	
 * 		
 * 		
 * 	
 * 	
 * 		
 * 		
 * 	
 * 	
 * 		
 * 		
 * 	
 * 	
 * 		
 * 		
 * 	
 * 	
 * 		
 * 		
 * 	
 * 	
 * 		
 * 		
 * 	
 * 
FirstnamePoints
Jill50
Eve94
Peter34
Paul67
Pierre12
Jacques90
John32
Rob1
* * @example * var options = { * sortable: true * }; * * var butorTable = $('table').ButorTable(options); **/ (function($) { var defaults = { xyz: true }; var bst = function(table, options) { var options = $.extend({}, defaults, options); var table = $(table); var thead = table.find('thead:first-child'); if (thead.length === 0) { LOGGER.warn('$.fn.ButorTable: tag not found.'); } var _colWidth = []; var _resizeTimer = null; var curSorting; var container = $('
' + '
' + '
'); /** * @method init * @memberof $(selector).ButorTable# * @description Initializes the table. * @access private */ var init = function(table, options) { var parent = table.parent(); container.insertBefore(table); if (table.hasClass('table-bordered')) { table.removeClass('table-bordered'); container.addClass('table-bordered'); } table.remove().appendTo(container.find('.butor-table-body')); thead.css('top', 0); table.bind("sortEnd", function(evt) { updateSortFlag(); }); options.sortable && table.tablesorter && table.tablesorter(options.sorterOptions); container.scroll(function() { var y = container.scrollTop(); //App.info(y); thead.css('top', y); }); resize(); }; /** * @method updateSortFlag * @memberof $(selector).ButorTable# * @description Updates all the sort flags. * @access private */ var updateSortFlag = function() { var sel = thead.find('th'); var nextIdx = 0; sel.each(function(i, e) { var je = $(e); if (je.hasClass('headerSortUp') || je.hasClass('headerSortDown')) { if (je.attr('sortIdx')) { var ti = parseInt(je.attr('sortIdx')); nextIdx = ti > nextIdx ? ti : nextIdx; } else { je.addClass('multiColSort'); } } else { je.removeAttr('sortIdx').removeClass('multiColSort'); } je.find('.multiSortColBadge').remove(); }); sel = thead.find('th.multiColSort'); if (sel.length == 1) { // start a new set of sorted col sel.removeAttr('sortIdx').find('.multiSortColBadge').remove(); nextIdx = 0; } sel.each(function(i, e) { var je = $(e); var idx = je.attr('sortIdx') if (!idx) { nextIdx += 1; idx = nextIdx; je.attr('sortIdx', idx); } // show badges if there is 2 or more if (sel.length > 1) { var badge = $('
' + idx + '
'); if (options['sortBadgeTitle']) { badge.attr('title', options['sortBadgeTitle']).tooltip(); } je.append(badge); } }); curSorting = []; thead.find('th').each(function(i, e) { var je = $(this); var idx = je.attr('sortIdx'); if (idx) { var dir = je.hasClass('headerSortDown') ? 0 : 1; curSorting[parseInt(idx) - 1] = [i, dir]; } }); }; /** * @method resize * @memberof $(selector).ButorTable# * @description Resizes the table. * * @example * butorTable.ButorTable('resize'); */ var resize = function() { // should let the table update & render before resizing if (_resizeTimer) { clearTimeout(_resizeTimer); } _resizeTimer = setTimeout(_resize, 100); } var headerRow; /** * @method _resize * @memberof $(selector).ButorTable# * @description Resizes the table (Logic). * @access private */ var _resize = function() { // check if there is a table header if (!thead[0] || !thead.find('th')[0]) return; clearTimeout(_resizeTimer); _resizeTimer = null; var tb = table.find('tbody'); var isEmpty = tb.find('tr:first').length == 0; var cws = []; thead.find("tr th").css('width', '').css('min-width', ''); if (!headerRow) { var row = thead.find("tr").clone().html(); row = row.replace(/th/g, 'td'); headerRow = $('' + row + ''); } headerRow.find('td').removeAttr('class').removeAttr('style').css( 'font-weight', 'bold'); headerRow.removeAttr('class').removeAttr('style'); tb.append(headerRow); container.find(".butor-table-body").css('width', ''); thead.css('width', ''); thead.find("tr").css('width', ''); var refTr = table.find('tbody tr.butor-table-trw-ref'); if (refTr.length == 0) { refTr = table.find('tbody tr:first').addClass('butor-table-trw-ref'); } var tw = 0; var lastThIndex = thead.find("tr th").length - 1; refTr.find("td").css('width', '').css('min-width', '').each(function(i, e) { var je = $(e); var fw = _colWidth[i]; var tdw = je.width(); fw = fw || tdw; cws.push(fw); if (i < lastThIndex) { je.width(fw).css('min-width', fw); if (je.width() > fw) { // column cannot be as narrow as expected, so adjust to it (wider) cws[i] = fw = je.width(); je.width(fw).css('min-width', fw); } } tw += fw; }); var cw = container.width(); if (tw < cw) { tw = cw; } // if vertical scroll bar is visible the reduce width to avoid horizontal scroll bar if (container.height() < table.find('tbody').height()) { tw -= 14; //-14 is ~ vertical s.b. width } container.find(".butor-table-body").css('width', tw); var tbw = table.find("tbody").width(); thead.css('width', tbw).css('min-width', tbw); thead.find("tr").css('width', tbw); thead.find("tr th").each(function(i, e) { var w = refTr.find("td:eq(" + i + ")").width(); if (i < lastThIndex) { $(e).width(w).css('min-width', w); } }); headerRow.remove(); var hh = thead.height(); container.css('padding-top', hh); }; /** * @method sort * @memberof $(selector).ButorTable# * @description Sorts the table. * @param {Array>} sorting - Specified columns to sort. * @example * butorTable.ButorTable('sort', [[1,0], [0,0]]); */ var sort = function(sorting) { var sorting = sorting || curSorting; //[[2,1],[0,0]]; if (!options.sortable && !sorting) { return; } if (table.find("tbody tr:first td").length > 0) { table.trigger("sorton", [sorting]); } curSorting = sorting; }; /** * @method setHeight * @memberof $(selector).ButorTable# * @description Sets the height of the table. * @param {Number|String} height - Height of the table. * @example * $(selector).ButorTable('setHeight', 20); * butorTable.ButorTable('setHeight', '100%'); */ var setHeight = function(h) { container.height(h); resize(); }; /** * @method setCss * @memberof $(selector).ButorTable# * @description Sets CSS to the container of the table. * @param {String} attribute - CSS attribute. * @param {String} value - CSS value. * @example * butorTable.ButorTable('setCss', 'border', '1px solid red'); */ var setCss = function(a, v) { container.css(a, v); }; /** * @method addClass * @memberof $(selector).ButorTable# * @description Adds class to the container of the table. * @param {String} class - Class name. * * @example * .test { * border: 1px solid red; * } * * @example * butorTable.ButorTable('test'); */ var addClass = function(cls) { container.addClass(cls); }; /** * @method setColWidth * @memberof $(selector).ButorTable# * @description Sets width of the specified column. * @param {Number} columnIndex - Index of the column. * @param {Number} width - Width of the column. * * @example * butorTable.ButorTable('setColWidth', '0', '10'); */ var setColWidth = function(i, w) { _colWidth[i] = w; resize(); }; /** * @method update * @memberof $(selector).ButorTable# * @description Updates the table. * * @example * butorTable.ButorTable('update'); */ var update = function() { table && options.sortable && table.trigger("update") && // should let the table update & render before sorting setTimeout(sort, 150); _resize(); }; /** * @method mask * @memberof $(selector).ButorTable# * @description Masks the table with a message. * @param {String} msg - Message on the masked table. * * @example * butorTable.ButorTable('mask', 'Masked table.'); */ var mask = function(msg) { container.mask(msg); }; /** * @method unmask * @memberof $(selector).ButorTable# * @description Unmasks the table. * * @example * butorTable.ButorTable('unmask'); */ var unmask = function() { container.unmask(); }; /** * @method offset * @memberof $(selector).ButorTable# * @description Gets the offset of the table. * @return {Map} Map which contains the table offset. * * @example * butorTable.ButorTable('offset'); * // output: * {top: 0, left: 0} */ var offset = function() { return container.offset() }; init(table, options); return { 'setHeight': setHeight, 'setCss': setCss, 'addClass': addClass, 'resize': resize, 'sort': sort, 'offset': offset, 'update': update, 'setColWidth': setColWidth, 'mask': mask, 'unmask': unmask }; }; $.fn.ButorTable = function(method) { if (typeof method === 'object' || !method) { var options = method; return this.each(function() { var $this = $(this), data = $this.data('.ButorTable'); if (!data) { $this.data('.ButorTable', (new bst($this, options))); } }); }; var data = $(this).data('.ButorTable'); if (!data) { $.error('jQuery.ButorTable is not initialised yet!'); } if (data[method]) { var ret = data[method].apply(this, Array.prototype.slice.call(arguments, 1)); if (!ret) { return $(this); } else { return ret; } } else { $.error('Method ' + method + ' does not exist on jQuery.ButorTable'); } }; }(window.jQuery)); /** * @class TableCtxtMenu * @memberof butor * @description Contextual menu for tables. * * TableCtxtMenu is a contextual menu which appears when a table cell/row/item is hovered. * It needs to be attached to a table and a context menu as jQuery elements. * * @param {jQueryElement} table - jQuery element of the table used in the context. * @param {jQueryElement} ctxtMenu - jQuery element of the menu to attach to each element of the table. * * @example * *
* *
* * * * * * * * * * * * * *
#Name
1Paul
* * @example * // Initialization of the MenuCtxt * var table = $('#table'); * var ctxMenu = $('#ctxMenu'); * tableCtxMenu = new butor.TableCtxtMenu(table, ctxMenu); * * // Simple tests on the Menu * tableCtxMenu.setSelectionFields(['name', 'age']); * tableCtxMenu.bind('row-hovered', function(e) { * console.log('Hi, I am ', e.data); * }); // hover the item will display the message. * * tableCtxMenu.disable(); // hovering will not work anymore. */ butor.TableCtxtMenu = butor.Class.define({ _table: null, _ctxtMenu: null, _ctxtMenuTimer: null, _hideCtxtMenu: null, _selectedItemFields: null, _hoveredItem: null, _hoveredRow: null, _enabled: true, construct: function(table, ctxtMenu) { this.base(); this._table = table; this._ctxtMenu = ctxtMenu; var self = this; /* this._ctxtMenu.hover(function() { self._ctxtMenu.removeClass('transparent'); }, function() { self._ctxtMenu.addClass('transparent'); }); */ this._ctxtMenuTimer = null; this._hideCtxtMenu = $.proxy(function() { this._ctxtMenu.fadeOut(); this._ctxtMenuTimer = null; }, this); this._showCtxtMenu = $.proxy(function(cc) { if (this._ctxtMenuTimer != null) { clearTimeout(this._ctxtMenuTimer); } var left = Math.min(cc.width, $('body').width()) - this._ctxtMenu.outerWidth(); var top = cc.top + cc.height / 2 - this._ctxtMenu.outerHeight() / 2; this._ctxtMenu.fadeIn().offset({ top: top }).css('left', left); this._ctxtMenuTimer = setTimeout(this._hideCtxtMenu, 5000); }, this); this._table.find('>tbody').delegate('>tr', 'hover', function() { self._rowHovered($(this)); }).delegate('tr', 'click', function() { self._rowHovered($(this)); //self._ctxtMenu.show(); //self._ctxtMenu.find('.dropdown-menu').toggle(); }); }, /** * @method _rowHovered * @access private * @memberof butor.TableCtxtMenu# * @description Linked right behaviour to the hovered row. * @param {Object} row - The hovered row. * @fires butor.TableCtxtMenu#row-hovered */ //TODO Specify row objects? _rowHovered: function(row) { if (!this._enabled) { return; } var cc = row.offset(); cc.width = row.width(); cc.height = row.height(); this._showCtxtMenu(cc); this._hoveredItem = {}; if (this._selectedItemFields) { for (var i in this._selectedItemFields) { var f = this._selectedItemFields[i]; this._hoveredItem[f] = row.attr(f); } } this._hoveredRow = row; this.fire('row-hovered', this._hoveredItem); }, /** * @method setSelectionFields * @memberof butor.TableCtxtMenu# * @description Sets the selection fields. * * The selected fileds need to match with the row attributes. * The matching is made from the jQuery function `$('tbody > tr').attr(selectedItemField)` for each selected fields you have set. * @param {String[]} selectedItemFields - Array of the selected fields. * @see {@link http://api.jquery.com/attr/ jQuery $.attr() function.} */ setSelectionFields: function(selectedItemFields) { this._selectedItemFields = selectedItemFields; }, /** * @method getHoveredItem * @memberof butor.TableCtxtMenu# * @description Gets the hovered item. * @return {Map} The hovered item. * It is described as a map which contains the attributes defined by {@link butor.TableCtxtMenu#setSelectionFields setSelectionFields}. */ getHoveredItem: function() { return this._hoveredItem; }, /** * @method getHoveredRow * @memberof butor.TableCtxtMenu# * @description Gets the hovered row. * @return {jQuerySelector[]} The hovered row. */ getHoveredRow: function() { return this._hoveredRow; }, /** * @method disable * @memberof butor.TableCtxtMenu# * @description Disables the contextual menu on the table. */ disable: function() { this._enabled = false; this._ctxtMenu && this._ctxtMenu.fadeOut(); }, /** * @method enable * @memberof butor.TableCtxtMenu# * @description Enables the contextual menu on the table. */ enable: function() { this._enabled = true; } }); /** * Notifies that a row is hovered. * @event butor.TableCtxtMenu#row-hovered * @param {Object} rowData - Hovered row data. */ butor = butor || {}; /** * @class Grid * @memberof butor * @description Wrapper of slickgrid. * @requires module:slickgrid/slick.core * @requires module:slickgrid/lib/jquery.event.drag-2.2 * @requires module:slickgrid/slick.grid * @requires module:slickgrid/slick.dataview * @requires module:slickgrid/plugins/slick.rowselectionmodel * @param {jQueryElement} jqe - jQueryElement where the grid is displayed. * @param {Map[]} columns - Array of columns of the table. These columns need to respect specific field in order to be created correctly. Take a look at {@link https://github.com/mleibman/SlickGrid/wiki/Column-Options SlickGrid Column Options} for more information about the `column` parameters. * @param {Map} options - Grid oprions. These options are not required and all have default options. Take a look at {@link https://github.com/mleibman/SlickGrid/wiki/Grid-Options SlickGrid Grid Options} for more information about the `options` parameters. * @param {Function} [comparator=null] - Multicolumn sorter of the grid. The comparator function compare two rows and a value which is '0' if the both rows are equal, '1' if the first row is strongger than the second, '-1' else. * @param {String} [defaultSortColumn=null] - The defaultSortColumn name. It enable sorting on a default column. **Be carefull, this functionnality works only if the `comparator` is set on true.** * @fires butor.Grid#sorted * @fires butor.Grid#mouseEntered * * @see http://www.butor.com/tmp/GridUpdate.wiki * @see http://www.butor.com/tmp/GridAdd.wiki * @see http://www.butor.com/tmp/GridRemove.wiki * @see http://www.butor.com/tmp/GridSelected.wiki * @example *
* * @example * var options = { * enableCellNavigation: true, * enableColumnReorder: false * }; * * var columns = [ * {id: 'c1', name: 'ID', field: 'id'}, * {id: 'c2', name: 'FirstName', field: 'firstName', sortable: true}, * {id: 'c3', name: 'LastName', field: 'lastName', sortable: true}, * {id: 'c4', name: 'Role', field: 'role', sortable: true} * ]; * * var comparer = function(a, b) { * return (a['firstName'] > b['firstName']) ? 1 : -1; * } * * var defaultSortColumn = columns[1]; * * // The items will be sorted with the 'FirstName' column. * var grid = new butor.Grid($('div.grid'), columns, options, comparer, defaultSortColumn['id']); * * // Uncaught Each data element must implement a unique 'id' property * var beatles_grid = [ * {id: 'b1', firstName: 'John', lastName: 'Lennon', role: 'Vocals'}, * {id: 'b2', firstName: 'Paul', lastName: 'McCartney', role: 'Vocals'}, * {id: 'b3', firstName: 'Georges', lastName: 'Harrison', role: 'Guitar'}, * {id: 'b4', firstName: 'Ringo', lastName: 'Starr', role: 'Drums'} * ]; * * // Avoid a grid repainting for each operation * grid.beginUpdate(); * for (var member of beatles_grid) grid.addItem(member); * grid.endUpdate(); * * var onSorted = function(e) { * $('p.sortExample').empty(); * var text = 'The grid has sorted on the field ' + e.data['field']; * text += ' by the column ' + defaultSortColumn['field'] + ''; * $('p.sortExample').html(text); * } * * var onEntered = function(e) { * console.log(e.data); * $('p.mouseExample').empty(); * var text = 'The mouse is over the cell: '; * text += 'grid[' + e.data['row'] + '][' + e.data['col'] + ']'; * $('p.mouseExample').html(text); * } * * grid.bind('sorted', onSorted); * grid.bind('mouseEntered', onEntered); * */ butor.Grid = butor.Class.define({ _jqe: null, _grid: null, _dataView: null, _columns: null, _options: null, _comparator: null, _defaultSortColumn: null, _sortedCols: null, _prevSelectedCount: 0, _updating: false, _itemMetadataProvider: null, construct: function(jqe, columns, options, comparator, defaultSortColumn) { this._jqe = jqe; this._columns = columns; this._options = options; this._comparator = comparator; this._defaultSortColumn = defaultSortColumn; if (this._columns) { for (var i = 0, c = this._columns.length; i < c; i += 1) { var col = this._columns[i]; if (!col.headerCssClass) { col.headerCssClass = 'align-center'; } else if (col.headerCssClass.indexOf('align') == -1) { col.headerCssClass += ' align-center'; } } } this._dataView = new Slick.Data.DataView(); this._dataView.getItemMetadata = $.proxy(function(rowIndex) { if (this._itemMetadataProvider) { return this._itemMetadataProvider(rowIndex); } }, this); var self = this; this._dataView.onRowCountChanged.subscribe(function(e, args) { self._grid.updateRowCount(); self._grid.render(); }); this._dataView.onRowsChanged.subscribe(function(e, args) { self._grid.invalidateRows(args.rows); self._grid.render(); }); this._grid = new Slick.Grid(this._jqe, this._dataView, this._columns, this ._options); this._grid.setSelectionModel(new Slick.RowSelectionModel({ selectActiveRow: true })); if (this._comparator) { if (this._defaultSortColumn) { this._grid.setSortColumn(this._defaultSortColumn, true); } this._grid.onSort.subscribe(function(e, args) { // remove old badges on muti col sort if any //sortCols exist only if multiColumnSort = true var sortCols = args.sortCols ? args.sortCols : [args.sortCol]; if (self._sortedCols) { var cols = self._grid.getColumns(); for (var i = 0, l = cols.length; i < l; i++) { if (self._sortedCols.indexOf(',' + cols[i].field) > -1) { var name = $('' + cols[i].name + ''); name.find('.multiSortColBadge').remove(); this.updateColumnHeader(cols[i].field, name.html()); } } } // draw new badges if muti col sort self._sortedCols = ','; if (sortCols.length > 1) { var cols = self._grid.getColumns(); for (var i = 0, l = sortCols.length; i < l; i++) { self._sortedCols += sortCols[i].sortCol.field + ','; if (!sortCols[i].sortCol.nameBak) { sortCols[i].sortCol.nameBak = sortCols[i].sortCol.name; } var ci = self._grid.getColumnIndex(sortCols[i].sortCol.id); var name = cols[ci].name + '
' + (i + 1) + '
'; this.updateColumnHeader(sortCols[i].sortCol.field, name); } } App.translateElem($(self.getContainerNode()).find('.slick-header'), self._options.bundleId); self._dataView.sort(self._comparator, args.sortAsc); self.fire('sorted', sortCols); }); App.translateElem($(this.getContainerNode()).find('.slick-header'), this._options .bundleId) } this._grid.onMouseEnter.subscribe(function(e, args) { var cell = this.getCellFromEvent(e); var node = $(this.getCellNode(cell.row, cell.cell)); var slickRow = node.parent(); slickRow.parent().find('.hovered').removeClass('hovered'); slickRow.addClass('hovered'); var rowData = this.getDataItem(cell.row); self.fire('mouseEntered', { 'row': cell.row, 'col': cell.cell, 'cellNode': node, 'rowData': rowData }); }); this._grid.onMouseLeave.subscribe(function(e, args) { var cell = this.getCellFromEvent(e); var node = $(this.getCellNode(cell.row, cell.cell)); //var slickRow = node.parent(); //slickRow.removeClass('hovered'); var rowData = this.getDataItem(cell.row); self.fire('mouseLeft', { 'cell': cell, 'node': node, 'rowData': rowData }); }); /* this._grid.onClick.subscribe(function (e, args) { var cell = this.getCellFromEvent(e); var node = $(this.getCellNode(cell.row, cell.cell)); var slickRow = node.parent(); slickRow.parent().find('.hovered').removeClass('hovered'); slickRow.addClass('hovered'); var rowData = this.getDataItem(cell.row); self.fire('click', { 'row' : cell.row, 'col' : cell.cell, 'cellNode' : node, 'rowData' : rowData }); }); */ this._grid.onSelectedRowsChanged.subscribe(function(e, args) { var rows = args.rows; if (self._prevSelectedCount == 0 && rows.length == 0) { // still no selection. return; } self._prevSelectedCount = rows.length; self.fire('selectionChanged', rows); }); this._grid.onScroll.subscribe(function(e, args) { var rr = self._grid.getRenderedRange(); var data = { 'bottomRowIndex': rr.bottom, 'topRowIndex': rr.top, 'leftPx': rr.leftPx, 'rightPx': rr.rightPx, 'scrollLeft': args.scrollLeft, 'scrollTop': args.scrollTop } self.fire('scroll', data); }); }, /** * @method setItemMetadataProvider * @memberof butor.Grid# * @description Sets the item metadata provider. * @param {Map} itemMetadataProvider - Item metadata provider. */ setItemMetadataProvider: function(itemMetadataProvider) { this._itemMetadataProvider = itemMetadataProvider; }, /** * @method getSortColumns * @memberof butor.Grid# * @description Gets the sort of the columns. * @return {Function} Column sorter. */ getSortColumns: function() { return this._grid.getSortColumns(); }, /** * @method addItem * @memberof butor.Grid# * @description Add an item in the grid. * @param {Map} item - Item to add. * @see http://www.butor.com/tmp/GridAdd.wiki * * @example *
*
* Add a new item * ID:
* First name:
* Last name:
* Role:
*
*
*
* * * * @example * var addNewItem = function() { * var id = document.getElementById('addIdInput').value; * var firstName = document.getElementById('addFirstNameInput').value; * var lastName = document.getElementById('addLastNameInput').value; * var role = document.getElementById('addRoleInput').value; * * var item = { * 'id': id, * 'firstName': firstName, * 'lastName': lastName, * 'role': role, * } * * grid.addItem(item); * } */ addItem: function(item) { this._dataView.addItem(item); }, /** * @method removeItem * @memberof butor.Grid# * @description Removes an item in the grid. * @param {Number} id - ID of the item to remove. * @see http://www.butor.com/tmp/GridRemove.wiki * * @example * * * @example * var removeSelectedItem = function() { * items = grid.getSelectedItems(); * * for (var i = 0; i < items.length; i++) { * grid.removeItem(items[i]['id']); * } * } */ removeItem: function(id) { this._dataView.deleteItem(id); }, /** * @method updateItem * @memberof butor.Grid# * @description Updates an item in the grid. * @param {Number} id - ID of the item to update. * @param {Map} item - Item to update. * @see http://www.butor.com/tmp/GridUpdate.wiki * * @example *
*
* Update an item * ID:
* First name:
* Last name:
* Role:
*
*
*
* * * @example * // After the grid initialisation * var opts = { * showEmpty: false, * idFN: 'id', * descFN: 'id', * sorted: true * }; * * // FILLSELECT MODIFY ITEMS !!!! * var items = []; * for (var i = 0; i < grid.getItems().length; i++) { * items.push($.extend({}, grid.getItems()[i])); * } * * butor.Utils.fillSelect($('#selectID'), items, opts); * * var changeSelect = function() { * var id = $('#selectID option:selected').val(); * var item = grid.getItemById(id); * * document.getElementById('updateFirstNameInput').value = item['firstName']; * document.getElementById('updateLastNameInput').value = item['lastName']; * document.getElementById('updateRoleInput').value = item['role']; * } * * var updateItem = function() { * var idUpdate = $('#selectID option:selected').val(); * var firstNameUpdate = document.getElementById('updateFirstNameInput').value; * var lastNameUpdate = document.getElementById('updateLastNameInput').value * var roleUpdate = document.getElementById('updateRoleInput').value; * * var item = { * id: idUpdate, * firstName: firstNameUpdate, * lastName: lastNameUpdate, * role: roleUpdate * } * * grid.updateItem(idUpdate, item); * } * */ updateItem: function(id, item) { this._dataView.updateItem(id, item); }, /** * @method beginUpdate * @memberof butor.Grid# * @description Begins a batch update of the grid. * During the update the grid won't refresh until the invocation of {@link butor.Grid#endUpdate `endUpdate()`}. */ beginUpdate: function() { this._updating = true; this._dataView.beginUpdate(); }, /** * @method endUpdate * @memberof butor.Grid# * @description Ends the batch update and refreshes the grid. */ endUpdate: function() { this._dataView.endUpdate(); this._updating = false; }, /** * @method isUpdating * @memberof butor.Grid# * @description Checks if the grid is updated. * @return True if the grid is updated. */ isUpdating: function() { return this._updating; }, /** * @method reSort * @memberof butor.Grid# * @description Sorts the grid. */ reSort: function() { this._dataView.reSort(); }, /** * @method clear * @memberof butor.Grid# * @description Clears the grid. */ clear: function() { this._dataView.setItems([]); this._grid.setSelectedRows([]); }, /** * @method getItems * @memberof butor.Grid# * @description Returns the original data array. * @return {Array} The original data array * @see SlickGrid DataView Methods {@link https://github.com/mleibman/SlickGrid/wiki/DataView#dataview-methods} * * @example * grid.getItems(); * // output: * [ * {id: 'b1', firstName: 'John', lastName: 'Lennon', role: 'Vocals'}, * {id: 'b2', firstName: 'Paul', lastName: 'McCartney', role: 'Vocals'}, * {id: 'b3', firstName: 'Georges', lastName: 'Harrison', role: 'Guitar'}, * {id: 'b4', firstName: 'Ringo', lastName: 'Starr', role: 'Drums'} * ] */ getItems: function() { return this._dataView.getItems(); }, /** * @method getItem * @memberof butor.Grid# * @description Gets an item from the row index. * @param {Number} row - Row index. * @returns {Object} An item attached to the row index. * @see SlickGrid DataView Methods {@link https://github.com/mleibman/SlickGrid/wiki/DataView#dataview-methods} * * @example * grid.getItem(1); * // output: * // {id: 'b2', firstName: 'Paul', lastName: 'McCartney', role: 'Vocals'} */ getItem: function(row) { return this._dataView.getItem(row); }, /** * @method getItemById * @memberof butor.Grid# * @description Gets an item at a given ID. * @param {Number} id - ID of the item to get. * @return {Object} The item. * @see SlickGrid DataView Methods {@link https://github.com/mleibman/SlickGrid/wiki/DataView#dataview-methods} * * @example * grid.getItemById('b2'); * // output: * // {id: 'b2', firstName: 'Paul', lastName: 'McCartney', role: 'Vocals'} */ getItemById: function(id) { return this._dataView.getItemById(id); }, /** * @method size * @memberof butor.Grid# * @description Gets the number of data items in the set. * @return {Number} The number of data items. * @see SlickGrid DataView Methods {@link https://github.com/mleibman/SlickGrid/wiki/DataView#core-concepts} */ size: function() { return this._dataView.getLength(); }, /** * @method resize * @memberof butor.Grid# * @description Resizes canevas which contain the grid. */ resize: function() { try { this._grid.resizeCanvas(); } catch (err) { this.logError(err); } }, /** * @method refresh * @memberof butor.Grid# * @description Refreshes the grid. */ refresh: function() { this._grid.invalidate(); this._grid.render(); }, /** * @method getContainerNode * @memberof butor.Grid# * @description Gets the container node of the grid. * @return {jQuerySelector} The container node. * @see {@link https://github.com/mleibman/SlickGrid/blob/e004912b5ce29ac0d0cb04df50fe66db5e3af9ea/slick.grid.js#L1319 SlickGrid/slick.grid.js#getContainerNode} * * @example * grid.getContainerNode(); * // output: * //
*/ getContainerNode: function() { return this._grid.getContainerNode(); }, /** * @method setSelectedRows * @memberof butor.Grid# * @description Sets the selected rows. * @param {Object[]} rows - Selected rows. * @see {@link https://github.com/mleibman/SlickGrid/blob/e004912b5ce29ac0d0cb04df50fe66db5e3af9ea/slick.grid.js#L3265 SlickGrid/slick.grid.js#getSelectedRows} */ setSelectedRows: function(rows) { this._grid.setSelectedRows(rows); }, /** * @method getSelectedRows * @memberof butor.Grid# * @description Gets the selected rows. * @return {Object[]} Selected rows. * @see {@link https://github.com/mleibman/SlickGrid/blob/e004912b5ce29ac0d0cb04df50fe66db5e3af9ea/slick.grid.js#L3258 SlickGrid/slick.grid.js#getSelectedRows} * @see http://www.butor.com/tmp/GridSelected.wiki * * @example *

Your selection:

*
    * * @example * var displayRows = function() { * var ul = document.getElementById('selectedLists'); * var rows = grid.getSelectedRows(); * var rowsText ='

    getSelectedRows() output: ['; * * for (var i = 0; i < rows.length; i++) { * rowsText += rows[i] + ', '; * } * * var li = document.createElement(li); * li.innerHTML = rowsText + ']

    '; * ul.appendChild(li); * } * * var onSelected = function() { * var ul = document.getElementById('selectedLists'); * ul.innerHTML = ''; * * displayRows(); * } * * grid.bind('selectionChanged', onSelected); */ getSelectedRows: function() { return this._grid.getSelectedRows(); }, /** * @method getSelectedItems * @memberof butor.Grid# * @description Gets the selected items. * @return {Object[]} The selected items. * @see http://www.butor.com/tmp/GridSelected.wiki * * @example *

    Your selection:

    *
      * * @example * var displayItems = function() { * var ul = document.getElementById('selectedLists'); * var items = grid.getSelectedItems(); * var itemsText ='

      getSelectedItems() output: ['; * * for (var i = 0; i < items.length; i++) { * itemsText += '{' * for (var key in items[i]) { * itemsText = itemsText + items[i][key] + ', '; * } * itemsText += '}, '; * } * * var li = document.createElement(li); * li.innerHTML = itemsText + ']

      '; * ul.appendChild(li); * } * * var onSelected = function() { * var ul = document.getElementById('selectedLists'); * ul.innerHTML = ''; * * displayItems(); * } * * grid.bind('selectionChanged', onSelected); */ getSelectedItems: function() { var items = []; var rows = this.getSelectedRows(); for (var i = 0, c = rows.length; i < c; i += 1) { items.push(this.getItem(rows[i])); } return items; }, /** * @method getSelectedIds * @memberof butor.Grid# * @description Gets the selected items. * @return {String[]} The selected ID. * * @example *

      Your selection:

      *
        * * @example * var displayIds = function() { * var ul = document.getElementById('selectedLists'); * var ids = grid.getSelectedIds(); * var idsText ='

        getSelectedIds() output: ['; * * for (var i = 0; i < ids.length; i++) { * idsText += ids[i] + ', '; * } * * var li = document.createElement(li); * li.innerHTML = idsText + ']

        '; * ul.appendChild(li); * } * * var onSelected = function() { * var ul = document.getElementById('selectedLists'); * ul.innerHTML = ''; * * displayIds(); * } * * grid.bind('selectionChanged', onSelected); */ getSelectedIds: function() { var items = []; var rows = this.getSelectedRows(); for (var i = 0, c = rows.length; i < c; i += 1) { items.push(this.getItem(rows[i]).id); } return items; }, /** * @method setSelectedIds * @memberof butor.Grid# * @description Sets the selected ID. * @param {String[]} idArray - Selected items by ID. */ setSelectedIds: function(idArray) { this._grid.setSelectedRows(this.mapIdsToRows(idArray)); }, /** * @method mapIdsToRows * @memberof butor.Grid# * @description Gets an array of rows by their index. * @param {Number[]} idArray - Array of index. * @see {@link https://github.com/mleibman/SlickGrid/blob/e004912b5ce29ac0d0cb04df50fe66db5e3af9ea/slick.dataview.js#L305 SlickGrid/slick.dataview.js#mapIdsToRows} */ mapIdsToRows: function(idArray) { return this._dataView.mapIdsToRows(idArray); }, /** * @method mapIdsToRows * @memberof butor.Grid# * @description Gets an array of index from an array of rows. * @param {Number[]} idArray - Array of rows. * @see {@link https://github.com/mleibman/SlickGrid/blob/e004912b5ce29ac0d0cb04df50fe66db5e3af9ea/slick.dataview.js#L317 SlickGrid/slick.dataview.js#mapRowsToIds} */ mapRowsToIds: function(rowArray) { return this._dataView.mapRowsToIds(rowArray); }, /** * @method showMoreRowsHintPopover * @memberof butor.Grid# * @description Shows an Hint Popover if the table is rendered on several pages. */ showMoreRowsHintPopover: function() { try { //popover to indicate how to get more rows (~ next page) var val = $.cookie("butor-tsdmrh"); if (val != null) { // user got it. on this computer/browser. return; } var gridNode = $(this.getContainerNode()); if (gridNode.find('.butor-tsdmrh').length > 0) { return; } var poperAnchor = $( '
        '); gridNode.append(poperAnchor); poperAnchor.popover({ 'title': 'More rows!', 'placement': 'left', 'html': true, 'trigger': 'manual', 'animation': true, 'content': 'Scroll to bottom to load more rows' + '
        ' }).popover('show'); App.translateElem(gridNode, this._options.bundleId); gridNode.find('.butor-tsdmrh').click(function() { poperAnchor.popover('destroy'); poperAnchor.remove(); $.cookie("butor-tsdmrh", "1", { 'expires': 60 }); }); } catch (err) { this.logError(err); } }, /** * @method tr * @memberof butor.Grid# * @description Translator with the grid bundle. */ tr: function(txt) { return App.tr(txt, this._options.bundleId); } }); /** * Grid sorted event. * @event butor.Grid#sorted * @param {Object} sortCol - The column object from the {@link https://github.com/mleibman/SlickGrid SlickGrid library}. * @param {boolean} sortCol.defaultSortAsc - Switch for ascendant sort. * @param {string} sortCol.field - Name of the column. * @param {boolean} sortCol.focusable - Switch for activate column focus. * @param {string} sortCol.headerCssClass - CSS class of the column header. * @param {string} sortCol.id - Id of the column. * @param {number} sortCol.minWidth - Minimal width of the column. * @param {string} sortCol.name - Name of the column. * @param {boolean} sortCol.rerenderOnResize - Switch for column rerender on resize. * @param {boolean} sortCol.resizable - Switch for allow column resizing. * @param {boolean} sortCol.selectable - Switch for allow column selection. * @param {boolean} sortCol.sortable - Switch for allow column sorting. * @param {number} sortCol.width - Width of the column. * @see {@link https://github.com/mleibman/SlickGrid/blob/e004912b5ce29ac0d0cb04df50fe66db5e3af9ea/slick.grid.js#L659 SlickGrid colSort Object} */ /** * Grid selectionChanged event. * @event butor.Grid#selectionChanged * @param {number} index - Selected row index. */ /** * Grid mouseEntered event. * @event butor.Grid#mouseEntered * @param {Map} tableInfo - Map of overflown elements. * @param {Number} tableInfo.row - Number of the overflown row. * @param {Number} tableInfo.col - Number of the overflown column. * @param {jQuerySelector} tableInfo.cellNode - Overflown element. * @param {Map} tableInfo.rowData - Overflown item. */ //# sourceURL=butor.table.js




        © 2015 - 2024 Weber Informatics LLC | Privacy Policy