jquery.bootgrid.js 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748
  1. /*!
  2. * jQuery Bootgrid v1.1.3 - 10/21/2014
  3. * Copyright (c) 2014 Rafael Staib (http://www.jquery-bootgrid.com)
  4. * Licensed under MIT http://www.opensource.org/licenses/MIT
  5. */
  6. ;(function ($, window, undefined)
  7. {
  8. /*jshint validthis: true */
  9. "use strict";
  10. // GRID INTERNAL FIELDS
  11. // ====================
  12. var namespace = ".rs.jquery.bootgrid";
  13. // GRID INTERNAL FUNCTIONS
  14. // =====================
  15. function appendRow(row)
  16. {
  17. var that = this;
  18. function exists(item)
  19. {
  20. return that.identifier && item[that.identifier] === row[that.identifier];
  21. }
  22. if (!this.rows.contains(exists))
  23. {
  24. this.rows.push(row);
  25. return true;
  26. }
  27. return false;
  28. }
  29. function getParams(context)
  30. {
  31. return (context) ? $.extend({}, this.cachedParams, { ctx: context }) :
  32. this.cachedParams;
  33. }
  34. function getRequest()
  35. {
  36. var request = {
  37. current: this.current,
  38. rowCount: this.rowCount,
  39. sort: this.sort,
  40. searchPhrase: this.searchPhrase
  41. },
  42. post = this.options.post;
  43. post = ($.isFunction(post)) ? post() : post;
  44. return this.options.requestHandler($.extend(true, request, post));
  45. }
  46. function getCssSelector(css)
  47. {
  48. return "." + $.trim(css).replace(/\s+/gm, ".");
  49. }
  50. function getUrl()
  51. {
  52. var url = this.options.url;
  53. return ($.isFunction(url)) ? url() : url;
  54. }
  55. function init()
  56. {
  57. this.element.trigger("initialize" + namespace);
  58. loadColumns.call(this); // Loads columns from HTML thead tag
  59. this.selection = this.options.selection && this.identifier != null;
  60. loadRows.call(this); // Loads rows from HTML tbody tag if ajax is false
  61. prepareTable.call(this);
  62. renderTableHeader.call(this);
  63. renderSearchField.call(this);
  64. renderActions.call(this);
  65. loadData.call(this);
  66. this.element.trigger("initialized" + namespace);
  67. }
  68. function highlightAppendedRows(rows)
  69. {
  70. if (this.options.highlightRows)
  71. {
  72. // todo: implement
  73. }
  74. }
  75. function isVisible(column)
  76. {
  77. return column.visible;
  78. }
  79. function loadColumns()
  80. {
  81. var that = this,
  82. firstHeadRow = this.element.find("thead > tr").first(),
  83. sorted = false;
  84. /*jshint -W018*/
  85. firstHeadRow.children().each(function ()
  86. {
  87. var $this = $(this),
  88. data = $this.data(),
  89. column = {
  90. id: data.columnId,
  91. identifier: that.identifier == null && data.identifier || false,
  92. converter: that.options.converters[data.converter || data.type] || that.options.converters["string"],
  93. text: $this.text(),
  94. align: data.align || "left",
  95. headerAlign: data.headerAlign || "left",
  96. cssClass: data.cssClass || "",
  97. headerCssClass: data.headerCssClass || "",
  98. formatter: that.options.formatters[data.formatter] || null,
  99. order: (!sorted && (data.order === "asc" || data.order === "desc")) ? data.order : null,
  100. searchable: !(data.searchable === false), // default: true
  101. sortable: !(data.sortable === false), // default: true
  102. visible: !(data.visible === false) // default: true
  103. };
  104. that.columns.push(column);
  105. if (column.order != null)
  106. {
  107. that.sort[column.id] = column.order;
  108. }
  109. // Prevents multiple identifiers
  110. if (column.identifier)
  111. {
  112. that.identifier = column.id;
  113. that.converter = column.converter;
  114. }
  115. // ensures that only the first order will be applied in case of multi sorting is disabled
  116. if (!that.options.multiSort && column.order !== null)
  117. {
  118. sorted = true;
  119. }
  120. });
  121. /*jshint +W018*/
  122. }
  123. /*
  124. response = {
  125. current: 1,
  126. rowCount: 10,
  127. rows: [{}, {}],
  128. sort: [{ "columnId": "asc" }],
  129. total: 101
  130. }
  131. */
  132. function loadData()
  133. {
  134. var that = this,
  135. request = getRequest.call(this),
  136. url = getUrl.call(this);
  137. if (this.options.ajax && (url == null || typeof url !== "string" || url.length === 0))
  138. {
  139. throw new Error("Url setting must be a none empty string or a function that returns one.");
  140. }
  141. this.element._bgBusyAria(true).trigger("load" + namespace);
  142. showLoading.call(this);
  143. function containsPhrase(row)
  144. {
  145. var column,
  146. searchPattern = new RegExp(that.searchPhrase, (that.options.caseSensitive) ? "g" : "gi");
  147. for (var i = 0; i < that.columns.length; i++)
  148. {
  149. column = that.columns[i];
  150. if (column.searchable && column.visible &&
  151. column.converter.to(row[column.id]).search(searchPattern) > -1)
  152. {
  153. return true;
  154. }
  155. }
  156. return false;
  157. }
  158. function update(rows, total)
  159. {
  160. that.currentRows = rows;
  161. that.total = total;
  162. that.totalPages = Math.ceil(total / that.rowCount);
  163. if (!that.options.keepSelection)
  164. {
  165. that.selectedRows = [];
  166. }
  167. renderRows.call(that, rows);
  168. renderInfos.call(that);
  169. renderPagination.call(that);
  170. that.element._bgBusyAria(false).trigger("loaded" + namespace);
  171. }
  172. if (this.options.ajax)
  173. {
  174. // aborts the previous ajax request if not already finished or failed
  175. if (that.xqr)
  176. {
  177. that.xqr.abort();
  178. }
  179. that.xqr = $.post(url, request, function (response)
  180. {
  181. that.xqr = null;
  182. if (typeof (response) === "string")
  183. {
  184. response = $.parseJSON(response);
  185. }
  186. response = that.options.responseHandler(response);
  187. that.current = response.current;
  188. update(response.rows, response.total);
  189. }).fail(function (jqXHR, textStatus, errorThrown)
  190. {
  191. that.xqr = null;
  192. if (textStatus !== "abort")
  193. {
  194. renderNoResultsRow.call(that); // overrides loading mask
  195. that.element._bgBusyAria(false).trigger("loaded" + namespace);
  196. }
  197. });
  198. }
  199. else
  200. {
  201. var rows = (this.searchPhrase.length > 0) ? this.rows.where(containsPhrase) : this.rows,
  202. total = rows.length;
  203. if (this.rowCount !== -1)
  204. {
  205. rows = rows.page(this.current, this.rowCount);
  206. }
  207. // todo: improve the following comment
  208. // setTimeout decouples the initialization so that adding event handlers happens before
  209. window.setTimeout(function () { update(rows, total); }, 10);
  210. }
  211. }
  212. function loadRows()
  213. {
  214. if (!this.options.ajax)
  215. {
  216. var that = this,
  217. rows = this.element.find("tbody > tr");
  218. rows.each(function ()
  219. {
  220. var $this = $(this),
  221. cells = $this.children("td"),
  222. row = {};
  223. $.each(that.columns, function (i, column)
  224. {
  225. row[column.id] = column.converter.from(cells.eq(i).text());
  226. });
  227. appendRow.call(that, row);
  228. });
  229. this.total = this.rows.length;
  230. this.totalPages = (this.rowCount === -1) ? 1 :
  231. Math.ceil(this.total / this.rowCount);
  232. sortRows.call(this);
  233. }
  234. }
  235. function prepareTable()
  236. {
  237. var tpl = this.options.templates,
  238. wrapper = (this.element.parent().hasClass(this.options.css.responsiveTable)) ?
  239. this.element.parent() : this.element;
  240. this.element.addClass(this.options.css.table);
  241. // checks whether there is an tbody element; otherwise creates one
  242. if (this.element.children("tbody").length === 0)
  243. {
  244. this.element.append(tpl.body);
  245. }
  246. if (this.options.navigation & 1)
  247. {
  248. this.header = $(tpl.header.resolve(getParams.call(this, { id: this.element._bgId() + "-header" })));
  249. wrapper.before(this.header);
  250. }
  251. if (this.options.navigation & 2)
  252. {
  253. this.footer = $(tpl.footer.resolve(getParams.call(this, { id: this.element._bgId() + "-footer" })));
  254. wrapper.after(this.footer);
  255. }
  256. }
  257. function renderActions()
  258. {
  259. if (this.options.navigation !== 0)
  260. {
  261. var css = this.options.css,
  262. selector = getCssSelector(css.actions),
  263. headerActions = this.header.find(selector),
  264. footerActions = this.footer.find(selector);
  265. if ((headerActions.length + footerActions.length) > 0)
  266. {
  267. var that = this,
  268. tpl = this.options.templates,
  269. actions = $(tpl.actions.resolve(getParams.call(this)));
  270. // Refresh Button
  271. if (this.options.ajax)
  272. {
  273. var refreshIcon = tpl.icon.resolve(getParams.call(this, { iconCss: css.iconRefresh })),
  274. refresh = $(tpl.actionButton.resolve(getParams.call(this,
  275. { content: refreshIcon, text: this.options.labels.refresh })))
  276. .on("click" + namespace, function (e)
  277. {
  278. // todo: prevent multiple fast clicks (fast click detection)
  279. e.stopPropagation();
  280. that.current = 1;
  281. loadData.call(that);
  282. });
  283. actions.append(refresh);
  284. }
  285. // Row count selection
  286. renderRowCountSelection.call(this, actions);
  287. // Column selection
  288. renderColumnSelection.call(this, actions);
  289. replacePlaceHolder.call(this, headerActions, actions, 1);
  290. replacePlaceHolder.call(this, footerActions, actions, 2);
  291. }
  292. }
  293. }
  294. function renderColumnSelection(actions)
  295. {
  296. if (this.options.columnSelection && this.columns.length > 1)
  297. {
  298. var that = this,
  299. css = this.options.css,
  300. tpl = this.options.templates,
  301. icon = tpl.icon.resolve(getParams.call(this, { iconCss: css.iconColumns })),
  302. dropDown = $(tpl.actionDropDown.resolve(getParams.call(this, { content: icon }))),
  303. selector = getCssSelector(css.dropDownItem),
  304. checkboxSelector = getCssSelector(css.dropDownItemCheckbox),
  305. itemsSelector = getCssSelector(css.dropDownMenuItems);
  306. $.each(this.columns, function (i, column)
  307. {
  308. var item = $(tpl.actionDropDownCheckboxItem.resolve(getParams.call(that,
  309. { name: column.id, label: column.text, checked: column.visible })))
  310. .on("click" + namespace, selector, function (e)
  311. {
  312. e.stopPropagation();
  313. var $this = $(this),
  314. checkbox = $this.find(checkboxSelector);
  315. if (!checkbox.prop("disabled"))
  316. {
  317. column.visible = checkbox.prop("checked");
  318. var enable = that.columns.where(isVisible).length > 1;
  319. $this.parents(itemsSelector).find(selector + ":has(" + checkboxSelector + ":checked)")
  320. ._bgEnableAria(enable).find(checkboxSelector)._bgEnableField(enable);
  321. that.element.find("tbody").empty(); // Fixes an column visualization bug
  322. renderTableHeader.call(that);
  323. loadData.call(that);
  324. }
  325. });
  326. dropDown.find(getCssSelector(css.dropDownMenuItems)).append(item);
  327. });
  328. actions.append(dropDown);
  329. }
  330. }
  331. function renderInfos()
  332. {
  333. if (this.options.navigation !== 0)
  334. {
  335. var selector = getCssSelector(this.options.css.infos),
  336. headerInfos = this.header.find(selector),
  337. footerInfos = this.footer.find(selector);
  338. if ((headerInfos.length + footerInfos.length) > 0)
  339. {
  340. var end = (this.current * this.rowCount),
  341. infos = $(this.options.templates.infos.resolve(getParams.call(this, {
  342. end: (this.total === 0 || end === -1 || end > this.total) ? this.total : end,
  343. start: (this.total === 0) ? 0 : (end - this.rowCount + 1),
  344. total: this.total
  345. })));
  346. replacePlaceHolder.call(this, headerInfos, infos, 1);
  347. replacePlaceHolder.call(this, footerInfos, infos, 2);
  348. }
  349. }
  350. }
  351. function renderNoResultsRow()
  352. {
  353. var tbody = this.element.children("tbody").first(),
  354. tpl = this.options.templates,
  355. count = this.columns.where(isVisible).length;
  356. if (this.selection)
  357. {
  358. count = count + 1;
  359. }
  360. tbody.html(tpl.noResults.resolve(getParams.call(this, { columns: count })));
  361. }
  362. function renderPagination()
  363. {
  364. if (this.options.navigation !== 0)
  365. {
  366. var selector = getCssSelector(this.options.css.pagination),
  367. headerPagination = this.header.find(selector)._bgShowAria(this.rowCount !== -1),
  368. footerPagination = this.footer.find(selector)._bgShowAria(this.rowCount !== -1);
  369. if (this.rowCount !== -1 && (headerPagination.length + footerPagination.length) > 0)
  370. {
  371. var tpl = this.options.templates,
  372. current = this.current,
  373. totalPages = this.totalPages,
  374. pagination = $(tpl.pagination.resolve(getParams.call(this))),
  375. offsetRight = totalPages - current,
  376. offsetLeft = (this.options.padding - current) * -1,
  377. startWith = ((offsetRight >= this.options.padding) ?
  378. Math.max(offsetLeft, 1) :
  379. Math.max((offsetLeft - this.options.padding + offsetRight), 1)),
  380. maxCount = this.options.padding * 2 + 1,
  381. count = (totalPages >= maxCount) ? maxCount : totalPages;
  382. renderPaginationItem.call(this, pagination, "first", "&laquo;", "first")
  383. ._bgEnableAria(current > 1);
  384. renderPaginationItem.call(this, pagination, "prev", "&lt;", "prev")
  385. ._bgEnableAria(current > 1);
  386. for (var i = 0; i < count; i++)
  387. {
  388. var pos = i + startWith;
  389. renderPaginationItem.call(this, pagination, pos, pos, "page-" + pos)
  390. ._bgEnableAria()._bgSelectAria(pos === current);
  391. }
  392. if (count === 0)
  393. {
  394. renderPaginationItem.call(this, pagination, 1, 1, "page-" + 1)
  395. ._bgEnableAria(false)._bgSelectAria();
  396. }
  397. renderPaginationItem.call(this, pagination, "next", "&gt;", "next")
  398. ._bgEnableAria(totalPages > current);
  399. renderPaginationItem.call(this, pagination, "last", "&raquo;", "last")
  400. ._bgEnableAria(totalPages > current);
  401. replacePlaceHolder.call(this, headerPagination, pagination, 1);
  402. replacePlaceHolder.call(this, footerPagination, pagination, 2);
  403. }
  404. }
  405. }
  406. function renderPaginationItem(list, uri, text, markerCss)
  407. {
  408. var that = this,
  409. tpl = this.options.templates,
  410. css = this.options.css,
  411. values = getParams.call(this, { css: markerCss, text: text, uri: "#" + uri }),
  412. item = $(tpl.paginationItem.resolve(values))
  413. .on("click" + namespace, getCssSelector(css.paginationButton), function (e)
  414. {
  415. e.stopPropagation();
  416. var $this = $(this),
  417. parent = $this.parent();
  418. if (!parent.hasClass("active") && !parent.hasClass("disabled"))
  419. {
  420. var commandList = {
  421. first: 1,
  422. prev: that.current - 1,
  423. next: that.current + 1,
  424. last: that.totalPages
  425. };
  426. var command = $this.attr("href").substr(1);
  427. that.current = commandList[command] || +command; // + converts string to int
  428. loadData.call(that);
  429. }
  430. $this.trigger("blur");
  431. });
  432. list.append(item);
  433. return item;
  434. }
  435. function renderRowCountSelection(actions)
  436. {
  437. var that = this,
  438. rowCountList = this.options.rowCount;
  439. function getText(value)
  440. {
  441. return (value === -1) ? that.options.labels.all : value;
  442. }
  443. if ($.isArray(rowCountList))
  444. {
  445. var css = this.options.css,
  446. tpl = this.options.templates,
  447. dropDown = $(tpl.actionDropDown.resolve(getParams.call(this, { content: this.rowCount }))),
  448. menuSelector = getCssSelector(css.dropDownMenu),
  449. menuTextSelector = getCssSelector(css.dropDownMenuText),
  450. menuItemsSelector = getCssSelector(css.dropDownMenuItems),
  451. menuItemSelector = getCssSelector(css.dropDownItemButton);
  452. $.each(rowCountList, function (index, value)
  453. {
  454. var item = $(tpl.actionDropDownItem.resolve(getParams.call(that,
  455. { text: getText(value), uri: "#" + value })))
  456. ._bgSelectAria(value === that.rowCount)
  457. .on("click" + namespace, menuItemSelector, function (e)
  458. {
  459. e.preventDefault();
  460. var $this = $(this),
  461. newRowCount = +$this.attr("href").substr(1);
  462. if (newRowCount !== that.rowCount)
  463. {
  464. // todo: sophisticated solution needed for calculating which page is selected
  465. that.current = 1; // that.rowCount === -1 ---> All
  466. that.rowCount = newRowCount;
  467. $this.parents(menuItemsSelector).children().each(function ()
  468. {
  469. var $item = $(this),
  470. currentRowCount = +$item.find(menuItemSelector).attr("href").substr(1);
  471. $item._bgSelectAria(currentRowCount === newRowCount);
  472. });
  473. $this.parents(menuSelector).find(menuTextSelector).text(getText(newRowCount));
  474. loadData.call(that);
  475. }
  476. });
  477. dropDown.find(menuItemsSelector).append(item);
  478. });
  479. actions.append(dropDown);
  480. }
  481. }
  482. function renderRows(rows)
  483. {
  484. if (rows.length > 0)
  485. {
  486. var that = this,
  487. css = this.options.css,
  488. tpl = this.options.templates,
  489. tbody = this.element.children("tbody").first(),
  490. allRowsSelected = true,
  491. html = "",
  492. cells = "",
  493. rowAttr = "",
  494. rowCss = "";
  495. $.each(rows, function (index, row)
  496. {
  497. cells = "";
  498. rowAttr = " data-row-id=\"" + ((that.identifier == null) ? index : row[that.identifier]) + "\"";
  499. rowCss = "";
  500. if (that.selection)
  501. {
  502. var selected = ($.inArray(row[that.identifier], that.selectedRows) !== -1),
  503. selectBox = tpl.select.resolve(getParams.call(that,
  504. { type: "checkbox", value: row[that.identifier], checked: selected }));
  505. cells += tpl.cell.resolve(getParams.call(that, { content: selectBox, css: css.selectCell }));
  506. allRowsSelected = (allRowsSelected && selected);
  507. if (selected)
  508. {
  509. rowCss += css.selected;
  510. rowAttr += " aria-selected=\"true\"";
  511. }
  512. }
  513. $.each(that.columns, function (j, column)
  514. {
  515. if (column.visible)
  516. {
  517. var value = ($.isFunction(column.formatter)) ?
  518. column.formatter.call(that, column, row) :
  519. column.converter.to(row[column.id]),
  520. cssClass = (column.cssClass.length > 0) ? " " + column.cssClass : "";
  521. cells += tpl.cell.resolve(getParams.call(that, {
  522. content: (value == null || value === "") ? "&nbsp;" : value,
  523. css: ((column.align === "right") ? css.right : (column.align === "center") ?
  524. css.center : css.left) + cssClass }));
  525. }
  526. });
  527. if (rowCss.length > 0)
  528. {
  529. rowAttr += " class=\"" + rowCss + "\"";
  530. }
  531. html += tpl.row.resolve(getParams.call(that, { attr: rowAttr, cells: cells }));
  532. });
  533. // sets or clears multi selectbox state
  534. that.element.find("thead " + getCssSelector(that.options.css.selectBox))
  535. .prop("checked", allRowsSelected);
  536. tbody.html(html);
  537. registerRowEvents.call(this, tbody);
  538. }
  539. else
  540. {
  541. renderNoResultsRow.call(this);
  542. }
  543. }
  544. function registerRowEvents(tbody)
  545. {
  546. var that = this,
  547. selectBoxSelector = getCssSelector(this.options.css.selectBox);
  548. if (this.selection)
  549. {
  550. tbody.off("click" + namespace, selectBoxSelector)
  551. .on("click" + namespace, selectBoxSelector, function(e)
  552. {
  553. e.stopPropagation();
  554. var $this = $(this),
  555. id = that.converter.from($this.val());
  556. if ($this.prop("checked"))
  557. {
  558. that.select([id]);
  559. }
  560. else
  561. {
  562. that.deselect([id]);
  563. }
  564. });
  565. }
  566. tbody.off("click" + namespace, "> tr")
  567. .on("click" + namespace, "> tr", function(e)
  568. {
  569. e.stopPropagation();
  570. var $this = $(this),
  571. id = (that.identifier == null) ? $this.data("row-id") :
  572. that.converter.from($this.data("row-id") + ""),
  573. row = (that.identifier == null) ? that.currentRows[id] :
  574. that.currentRows.first(function (item) { return item[that.identifier] === id; });
  575. if (that.selection && that.options.rowSelect)
  576. {
  577. if ($this.hasClass(that.options.css.selected))
  578. {
  579. that.deselect([id]);
  580. }
  581. else
  582. {
  583. that.select([id]);
  584. }
  585. }
  586. that.element.trigger("click" + namespace, [that.columns, row]);
  587. });
  588. }
  589. function renderSearchField()
  590. {
  591. if (this.options.navigation !== 0)
  592. {
  593. var css = this.options.css,
  594. selector = getCssSelector(css.search),
  595. headerSearch = this.header.find(selector),
  596. footerSearch = this.footer.find(selector);
  597. if ((headerSearch.length + footerSearch.length) > 0)
  598. {
  599. var that = this,
  600. tpl = this.options.templates,
  601. timer = null, // fast keyup detection
  602. currentValue = "",
  603. searchFieldSelector = getCssSelector(css.searchField),
  604. search = $(tpl.search.resolve(getParams.call(this))),
  605. searchField = (search.is(searchFieldSelector)) ? search :
  606. search.find(searchFieldSelector);
  607. searchField.on("keyup" + namespace, function (e)
  608. {
  609. e.stopPropagation();
  610. var newValue = $(this).val();
  611. if (currentValue !== newValue)
  612. {
  613. currentValue = newValue;
  614. window.clearTimeout(timer);
  615. timer = window.setTimeout(function ()
  616. {
  617. that.search(newValue);
  618. }, 250);
  619. }
  620. });
  621. replacePlaceHolder.call(this, headerSearch, search, 1);
  622. replacePlaceHolder.call(this, footerSearch, search, 2);
  623. }
  624. }
  625. }
  626. function renderTableHeader()
  627. {
  628. var that = this,
  629. headerRow = this.element.find("thead > tr"),
  630. css = this.options.css,
  631. tpl = this.options.templates,
  632. html = "",
  633. sorting = this.options.sorting;
  634. if (this.selection)
  635. {
  636. var selectBox = (this.options.multiSelect) ?
  637. tpl.select.resolve(getParams.call(that, { type: "checkbox", value: "all" })) : "";
  638. html += tpl.rawHeaderCell.resolve(getParams.call(that, { content: selectBox,
  639. css: css.selectCell }));
  640. }
  641. $.each(this.columns, function (index, column)
  642. {
  643. if (column.visible)
  644. {
  645. var sortOrder = that.sort[column.id],
  646. iconCss = ((sorting && sortOrder && sortOrder === "asc") ? css.iconUp :
  647. (sorting && sortOrder && sortOrder === "desc") ? css.iconDown : ""),
  648. icon = tpl.icon.resolve(getParams.call(that, { iconCss: iconCss })),
  649. align = column.headerAlign,
  650. cssClass = (column.headerCssClass.length > 0) ? " " + column.headerCssClass : "";
  651. html += tpl.headerCell.resolve(getParams.call(that, {
  652. column: column, icon: icon, sortable: sorting && column.sortable && css.sortable || "",
  653. css: ((align === "right") ? css.right : (align === "center") ?
  654. css.center : css.left) + cssClass }));
  655. }
  656. });
  657. headerRow.html(html);
  658. // todo: create a own function for that piece of code
  659. if (sorting)
  660. {
  661. var sortingSelector = getCssSelector(css.sortable),
  662. iconSelector = getCssSelector(css.icon);
  663. headerRow.off("click" + namespace, sortingSelector)
  664. .on("click" + namespace, sortingSelector, function (e)
  665. {
  666. e.preventDefault();
  667. var $this = $(this),
  668. columnId = $this.data("column-id") || $this.parents("th").first().data("column-id"),
  669. sortOrder = that.sort[columnId],
  670. icon = $this.find(iconSelector);
  671. if (!that.options.multiSort)
  672. {
  673. $this.parents("tr").first().find(iconSelector).removeClass(css.iconDown + " " + css.iconUp);
  674. that.sort = {};
  675. }
  676. if (sortOrder && sortOrder === "asc")
  677. {
  678. that.sort[columnId] = "desc";
  679. icon.removeClass(css.iconUp).addClass(css.iconDown);
  680. }
  681. else if (sortOrder && sortOrder === "desc")
  682. {
  683. if (that.options.multiSort)
  684. {
  685. var newSort = {};
  686. for (var key in that.sort)
  687. {
  688. if (key !== columnId)
  689. {
  690. newSort[key] = that.sort[key];
  691. }
  692. }
  693. that.sort = newSort;
  694. icon.removeClass(css.iconDown);
  695. }
  696. else
  697. {
  698. that.sort[columnId] = "asc";
  699. icon.removeClass(css.iconDown).addClass(css.iconUp);
  700. }
  701. }
  702. else
  703. {
  704. that.sort[columnId] = "asc";
  705. icon.addClass(css.iconUp);
  706. }
  707. sortRows.call(that);
  708. loadData.call(that);
  709. });
  710. }
  711. // todo: create a own function for that piece of code
  712. if (this.selection && this.options.multiSelect)
  713. {
  714. var selectBoxSelector = getCssSelector(css.selectBox);
  715. headerRow.off("click" + namespace, selectBoxSelector)
  716. .on("click" + namespace, selectBoxSelector, function(e)
  717. {
  718. e.stopPropagation();
  719. if ($(this).prop("checked"))
  720. {
  721. that.select();
  722. }
  723. else
  724. {
  725. that.deselect();
  726. }
  727. });
  728. }
  729. }
  730. function replacePlaceHolder(placeholder, element, flag)
  731. {
  732. if (this.options.navigation & flag)
  733. {
  734. placeholder.each(function (index, item)
  735. {
  736. // todo: check how append is implemented. Perhaps cloning here is superfluous.
  737. $(item).before(element.clone(true)).remove();
  738. });
  739. }
  740. }
  741. function showLoading()
  742. {
  743. var tpl = this.options.templates,
  744. thead = this.element.children("thead").first(),
  745. tbody = this.element.children("tbody").first(),
  746. firstCell = tbody.find("tr > td").first(),
  747. padding = (this.element.height() - thead.height()) - (firstCell.height() + 20),
  748. count = this.columns.where(isVisible).length;
  749. if (this.selection)
  750. {
  751. count = count + 1;
  752. }
  753. tbody.html(tpl.loading.resolve(getParams.call(this, { columns: count })));
  754. if (this.rowCount !== -1 && padding > 0)
  755. {
  756. tbody.find("tr > td").css("padding", "20px 0 " + padding + "px");
  757. }
  758. }
  759. function sortRows()
  760. {
  761. var sortArray = [];
  762. function sort(x, y, current)
  763. {
  764. current = current || 0;
  765. var next = current + 1,
  766. item = sortArray[current];
  767. function sortOrder(value)
  768. {
  769. return (item.order === "asc") ? value : value * -1;
  770. }
  771. return (x[item.id] > y[item.id]) ? sortOrder(1) :
  772. (x[item.id] < y[item.id]) ? sortOrder(-1) :
  773. (sortArray.length > next) ? sort(x, y, next) : 0;
  774. }
  775. if (!this.options.ajax)
  776. {
  777. var that = this;
  778. for (var key in this.sort)
  779. {
  780. if (this.options.multiSort || sortArray.length === 0)
  781. {
  782. sortArray.push({
  783. id: key,
  784. order: this.sort[key]
  785. });
  786. }
  787. }
  788. if (sortArray.length > 0)
  789. {
  790. this.rows.sort(sort);
  791. }
  792. }
  793. }
  794. // GRID PUBLIC CLASS DEFINITION
  795. // ====================
  796. /**
  797. * Represents the jQuery Bootgrid plugin.
  798. *
  799. * @class Grid
  800. * @constructor
  801. * @param element {Object} The corresponding DOM element.
  802. * @param options {Object} The options to override default settings.
  803. * @chainable
  804. **/
  805. var Grid = function(element, options)
  806. {
  807. this.element = $(element);
  808. this.origin = this.element.clone();
  809. this.options = $.extend(true, {}, Grid.defaults, this.element.data(), options);
  810. // overrides rowCount explicitly because deep copy ($.extend) leads to strange behaviour
  811. var rowCount = this.options.rowCount = this.element.data().rowCount || options.rowCount || this.options.rowCount;
  812. this.columns = [];
  813. this.current = 1;
  814. this.currentRows = [];
  815. this.identifier = null; // The first column ID that is marked as identifier
  816. this.selection = false;
  817. this.converter = null; // The converter for the column that is marked as identifier
  818. this.rowCount = ($.isArray(rowCount)) ? rowCount[0] : rowCount;
  819. this.rows = [];
  820. this.searchPhrase = "";
  821. this.selectedRows = [];
  822. this.sort = {};
  823. this.total = 0;
  824. this.totalPages = 0;
  825. this.cachedParams = {
  826. lbl: this.options.labels,
  827. css: this.options.css,
  828. ctx: {}
  829. };
  830. this.header = null;
  831. this.footer = null;
  832. this.xqr = null;
  833. // todo: implement cache
  834. };
  835. /**
  836. * An object that represents the default settings.
  837. * There are two ways to override the sub-properties.
  838. * Either by doing it generally (global) or on initialization.
  839. *
  840. * @static
  841. * @class defaults
  842. * @for Grid
  843. * @example
  844. * // Global approach
  845. * $.bootgrid.defaults.selection = true;
  846. * @example
  847. * // Initialization approach
  848. * $("#bootgrid").bootgrid({ selection = true });
  849. **/
  850. Grid.defaults = {
  851. navigation: 3, // it's a flag: 0 = none, 1 = top, 2 = bottom, 3 = both (top and bottom)
  852. padding: 2, // page padding (pagination)
  853. columnSelection: true,
  854. rowCount: [10, 25, 50, -1], // rows per page int or array of int (-1 represents "All")
  855. /**
  856. * Enables row selection (to enable multi selection see also `multiSelect`). Default value is `false`.
  857. *
  858. * @property selection
  859. * @type Boolean
  860. * @default false
  861. * @for defaults
  862. * @since 1.0.0
  863. **/
  864. selection: false,
  865. /**
  866. * Enables multi selection (`selection` must be set to `true` as well). Default value is `false`.
  867. *
  868. * @property multiSelect
  869. * @type Boolean
  870. * @default false
  871. * @for defaults
  872. * @since 1.0.0
  873. **/
  874. multiSelect: false,
  875. /**
  876. * Enables entire row click selection (`selection` must be set to `true` as well). Default value is `false`.
  877. *
  878. * @property rowSelect
  879. * @type Boolean
  880. * @default false
  881. * @for defaults
  882. * @since 1.1.0
  883. **/
  884. rowSelect: false,
  885. /**
  886. * Defines whether the row selection is saved internally on filtering, paging and sorting
  887. * (even if the selected rows are not visible).
  888. *
  889. * @property keepSelection
  890. * @type Boolean
  891. * @default false
  892. * @for defaults
  893. * @since 1.1.0
  894. **/
  895. keepSelection: false,
  896. highlightRows: false, // highlights new rows (find the page of the first new row)
  897. sorting: true,
  898. multiSort: false,
  899. ajax: false, // todo: find a better name for this property to differentiate between client-side and server-side data
  900. /**
  901. * Enriches the request object with additional properties. Either a `PlainObject` or a `Function`
  902. * that returns a `PlainObject` can be passed. Default value is `{}`.
  903. *
  904. * @property post
  905. * @type Object|Function
  906. * @default function (request) { return request; }
  907. * @for defaults
  908. * @deprecated Use instead `requestHandler`
  909. **/
  910. post: {}, // or use function () { return {}; } (reserved properties are "current", "rowCount", "sort" and "searchPhrase")
  911. /**
  912. * Sets the data URL to a data service (e.g. a REST service). Either a `String` or a `Function`
  913. * that returns a `String` can be passed. Default value is `""`.
  914. *
  915. * @property url
  916. * @type String|Function
  917. * @default ""
  918. * @for defaults
  919. **/
  920. url: "", // or use function () { return ""; }
  921. /**
  922. * Defines whether the search is case sensitive or insensitive.
  923. *
  924. * @property caseSensitive
  925. * @type Boolean
  926. * @default true
  927. * @for defaults
  928. * @since 1.1.0
  929. **/
  930. caseSensitive: true,
  931. // note: The following properties should not be used via data-api attributes
  932. /**
  933. * Transforms the JSON request object in what ever is needed on the server-side implementation.
  934. *
  935. * @property requestHandler
  936. * @type Function
  937. * @default function (request) { return request; }
  938. * @for defaults
  939. * @since 1.1.0
  940. **/
  941. requestHandler: function (request) { return request; },
  942. /**
  943. * Transforms the response object into the expected JSON response object.
  944. *
  945. * @property responseHandler
  946. * @type Function
  947. * @default function (response) { return response; }
  948. * @for defaults
  949. * @since 1.1.0
  950. **/
  951. responseHandler: function (response) { return response; },
  952. /**
  953. * A list of converters.
  954. *
  955. * @property converters
  956. * @type Object
  957. * @for defaults
  958. * @since 1.0.0
  959. **/
  960. converters: {
  961. numeric: {
  962. from: function (value) { return +value; }, // converts from string to numeric
  963. to: function (value) { return value + ""; } // converts from numeric to string
  964. },
  965. string: {
  966. // default converter
  967. from: function (value) { return value; },
  968. to: function (value) { return value; }
  969. }
  970. },
  971. /**
  972. * Contains all css classes.
  973. *
  974. * @property css
  975. * @type Object
  976. * @for defaults
  977. **/
  978. css: {
  979. actions: "actions btn-group", // must be a unique class name or constellation of class names within the header and footer
  980. center: "text-center",
  981. columnHeaderAnchor: "column-header-anchor", // must be a unique class name or constellation of class names within the column header cell
  982. columnHeaderText: "text",
  983. dropDownItem: "dropdown-item", // must be a unique class name or constellation of class names within the actionDropDown,
  984. dropDownItemButton: "dropdown-item-button", // must be a unique class name or constellation of class names within the actionDropDown
  985. dropDownItemCheckbox: "dropdown-item-checkbox", // must be a unique class name or constellation of class names within the actionDropDown
  986. dropDownMenu: "dropdown btn-group", // must be a unique class name or constellation of class names within the actionDropDown
  987. dropDownMenuItems: "dropdown-menu pull-right", // must be a unique class name or constellation of class names within the actionDropDown
  988. dropDownMenuText: "dropdown-text", // must be a unique class name or constellation of class names within the actionDropDown
  989. footer: "bootgrid-footer container-fluid",
  990. header: "bootgrid-header container-fluid",
  991. icon: "icon glyphicon",
  992. iconColumns: "glyphicon-th-list",
  993. iconDown: "glyphicon-chevron-down",
  994. iconRefresh: "glyphicon-refresh",
  995. iconUp: "glyphicon-chevron-up",
  996. infos: "infos", // must be a unique class name or constellation of class names within the header and footer,
  997. left: "text-left",
  998. pagination: "pagination", // must be a unique class name or constellation of class names within the header and footer
  999. paginationButton: "button", // must be a unique class name or constellation of class names within the pagination
  1000. /**
  1001. * CSS class to select the parent div which activates responsive mode.
  1002. *
  1003. * @property responsiveTable
  1004. * @type String
  1005. * @default "table-responsive"
  1006. * @for css
  1007. * @since 1.1.0
  1008. **/
  1009. responsiveTable: "table-responsive",
  1010. right: "text-right",
  1011. search: "search form-group", // must be a unique class name or constellation of class names within the header and footer
  1012. searchField: "search-field form-control",
  1013. selectBox: "select-box", // must be a unique class name or constellation of class names within the entire table
  1014. selectCell: "select-cell", // must be a unique class name or constellation of class names within the entire table
  1015. /**
  1016. * CSS class to highlight selected rows.
  1017. *
  1018. * @property selected
  1019. * @type String
  1020. * @default "active"
  1021. * @for css
  1022. * @since 1.1.0
  1023. **/
  1024. selected: "active",
  1025. sortable: "sortable",
  1026. table: "bootgrid-table table"
  1027. },
  1028. /**
  1029. * A dictionary of formatters.
  1030. *
  1031. * @property formatters
  1032. * @type Object
  1033. * @for defaults
  1034. * @since 1.0.0
  1035. **/
  1036. formatters: {},
  1037. /**
  1038. * Contains all labels.
  1039. *
  1040. * @property labels
  1041. * @type Object
  1042. * @for defaults
  1043. **/
  1044. labels: {
  1045. all: "All",
  1046. infos: "Showing {{ctx.start}} to {{ctx.end}} of {{ctx.total}} entries",
  1047. loading: "Loading...",
  1048. noResults: "No results found!",
  1049. refresh: "Refresh",
  1050. search: "Search"
  1051. },
  1052. /**
  1053. * Contains all templates.
  1054. *
  1055. * @property templates
  1056. * @type Object
  1057. * @for defaults
  1058. **/
  1059. templates: {
  1060. actionButton: "<button class=\"btn btn-default\" type=\"button\" title=\"{{ctx.text}}\">{{ctx.content}}</button>",
  1061. actionDropDown: "<div class=\"{{css.dropDownMenu}}\"><button class=\"btn btn-default dropdown-toggle\" type=\"button\" data-toggle=\"dropdown\"><span class=\"{{css.dropDownMenuText}}\">{{ctx.content}}</span> <span class=\"caret\"></span></button><ul class=\"{{css.dropDownMenuItems}}\" role=\"menu\"></ul></div>",
  1062. actionDropDownItem: "<li><a href=\"{{ctx.uri}}\" class=\"{{css.dropDownItem}} {{css.dropDownItemButton}}\">{{ctx.text}}</a></li>",
  1063. actionDropDownCheckboxItem: "<li><label class=\"{{css.dropDownItem}}\"><input name=\"{{ctx.name}}\" type=\"checkbox\" value=\"1\" class=\"{{css.dropDownItemCheckbox}}\" {{ctx.checked}} /> {{ctx.label}}</label></li>",
  1064. actions: "<div class=\"{{css.actions}}\"></div>",
  1065. body: "<tbody></tbody>",
  1066. cell: "<td class=\"{{ctx.css}}\">{{ctx.content}}</td>",
  1067. footer: "<div id=\"{{ctx.id}}\" class=\"{{css.footer}}\"><div class=\"row\"><div class=\"col-sm-6\"><p class=\"{{css.pagination}}\"></p></div><div class=\"col-sm-6 infoBar\"><p class=\"{{css.infos}}\"></p></div></div></div>",
  1068. header: "<div id=\"{{ctx.id}}\" class=\"{{css.header}}\"><div class=\"row\"><div class=\"col-sm-12 actionBar\"><p class=\"{{css.search}}\"></p><p class=\"{{css.actions}}\"></p></div></div></div>",
  1069. headerCell: "<th data-column-id=\"{{ctx.column.id}}\" class=\"{{ctx.css}}\"><a href=\"javascript:void(0);\" class=\"{{css.columnHeaderAnchor}} {{ctx.sortable}}\"><span class=\"{{css.columnHeaderText}}\">{{ctx.column.text}}</span>{{ctx.icon}}</a></th>",
  1070. icon: "<span class=\"{{css.icon}} {{ctx.iconCss}}\"></span>",
  1071. infos: "<div class=\"{{css.infos}}\">{{lbl.infos}}</div>",
  1072. loading: "<tr><td colspan=\"{{ctx.columns}}\" class=\"loading\">{{lbl.loading}}</td></tr>",
  1073. noResults: "<tr><td colspan=\"{{ctx.columns}}\" class=\"no-results\">{{lbl.noResults}}</td></tr>",
  1074. pagination: "<ul class=\"{{css.pagination}}\"></ul>",
  1075. paginationItem: "<li class=\"{{ctx.css}}\"><a href=\"{{ctx.uri}}\" class=\"{{css.paginationButton}}\">{{ctx.text}}</a></li>",
  1076. rawHeaderCell: "<th class=\"{{ctx.css}}\">{{ctx.content}}</th>", // Used for the multi select box
  1077. row: "<tr{{ctx.attr}}>{{ctx.cells}}</tr>",
  1078. search: "<div class=\"{{css.search}}\"><div class=\"input-group\"><span class=\"{{css.icon}} input-group-addon glyphicon-search\"></span> <input type=\"text\" class=\"{{css.searchField}}\" placeholder=\"{{lbl.search}}\" /></div></div>",
  1079. select: "<input name=\"select\" type=\"{{ctx.type}}\" class=\"{{css.selectBox}}\" value=\"{{ctx.value}}\" {{ctx.checked}} />"
  1080. }
  1081. };
  1082. /**
  1083. * Appends rows.
  1084. *
  1085. * @method append
  1086. * @param rows {Array} An array of rows to append
  1087. * @chainable
  1088. **/
  1089. Grid.prototype.append = function(rows)
  1090. {
  1091. if (this.options.ajax)
  1092. {
  1093. // todo: implement ajax DELETE
  1094. }
  1095. else
  1096. {
  1097. var appendedRows = [];
  1098. for (var i = 0; i < rows.length; i++)
  1099. {
  1100. if (appendRow.call(this, rows[i]))
  1101. {
  1102. appendedRows.push(rows[i]);
  1103. }
  1104. }
  1105. sortRows.call(this);
  1106. highlightAppendedRows.call(this, appendedRows);
  1107. loadData.call(this);
  1108. this.element.trigger("appended" + namespace, [appendedRows]);
  1109. }
  1110. return this;
  1111. };
  1112. /**
  1113. * Removes all rows.
  1114. *
  1115. * @method clear
  1116. * @chainable
  1117. **/
  1118. Grid.prototype.clear = function()
  1119. {
  1120. if (this.options.ajax)
  1121. {
  1122. // todo: implement ajax POST
  1123. }
  1124. else
  1125. {
  1126. var removedRows = $.extend([], this.rows);
  1127. this.rows = [];
  1128. this.current = 1;
  1129. this.total = 0;
  1130. loadData.call(this);
  1131. this.element.trigger("cleared" + namespace, [removedRows]);
  1132. }
  1133. return this;
  1134. };
  1135. /**
  1136. * Removes the control functionality completely and transforms the current state to the initial HTML structure.
  1137. *
  1138. * @method destroy
  1139. * @chainable
  1140. **/
  1141. Grid.prototype.destroy = function()
  1142. {
  1143. // todo: this method has to be optimized (the complete initial state must be restored)
  1144. $(window).off(namespace);
  1145. if (this.options.navigation & 1)
  1146. {
  1147. this.header.remove();
  1148. }
  1149. if (this.options.navigation & 2)
  1150. {
  1151. this.footer.remove();
  1152. }
  1153. this.element.before(this.origin).remove();
  1154. return this;
  1155. };
  1156. /**
  1157. * Resets the state and reloads rows.
  1158. *
  1159. * @method reload
  1160. * @chainable
  1161. **/
  1162. Grid.prototype.reload = function()
  1163. {
  1164. this.current = 1; // reset
  1165. loadData.call(this);
  1166. return this;
  1167. };
  1168. /**
  1169. * Removes rows by ids. Removes selected rows if no ids are provided.
  1170. *
  1171. * @method remove
  1172. * @param [rowsIds] {Array} An array of rows ids to remove
  1173. * @chainable
  1174. **/
  1175. Grid.prototype.remove = function(rowIds)
  1176. {
  1177. if (this.identifier != null)
  1178. {
  1179. var that = this;
  1180. if (this.options.ajax)
  1181. {
  1182. // todo: implement ajax DELETE
  1183. }
  1184. else
  1185. {
  1186. rowIds = rowIds || this.selectedRows;
  1187. var id,
  1188. removedRows = [];
  1189. for (var i = 0; i < rowIds.length; i++)
  1190. {
  1191. id = rowIds[i];
  1192. for (var j = 0; j < this.rows.length; j++)
  1193. {
  1194. if (this.rows[j][this.identifier] === id)
  1195. {
  1196. removedRows.push(this.rows[j]);
  1197. this.rows.splice(j, 1);
  1198. break;
  1199. }
  1200. }
  1201. }
  1202. this.current = 1; // reset
  1203. loadData.call(this);
  1204. this.element.trigger("removed" + namespace, [removedRows]);
  1205. }
  1206. }
  1207. return this;
  1208. };
  1209. /**
  1210. * Searches in all rows for a specific phrase (but only in visible cells).
  1211. *
  1212. * @method search
  1213. * @param phrase {String} The phrase to search for
  1214. * @chainable
  1215. **/
  1216. Grid.prototype.search = function(phrase)
  1217. {
  1218. if (this.searchPhrase !== phrase)
  1219. {
  1220. this.current = 1;
  1221. this.searchPhrase = phrase;
  1222. loadData.call(this);
  1223. }
  1224. return this;
  1225. };
  1226. /**
  1227. * Selects rows by ids. Selects all visible rows if no ids are provided.
  1228. * In server-side scenarios only visible rows are selectable.
  1229. *
  1230. * @method select
  1231. * @param [rowsIds] {Array} An array of rows ids to select
  1232. * @chainable
  1233. **/
  1234. Grid.prototype.select = function(rowIds)
  1235. {
  1236. if (this.selection)
  1237. {
  1238. rowIds = rowIds || this.currentRows.propValues(this.identifier);
  1239. var id, i,
  1240. selectedRows = [];
  1241. while (rowIds.length > 0 && !(!this.options.multiSelect && selectedRows.length === 1))
  1242. {
  1243. id = rowIds.pop();
  1244. if ($.inArray(id, this.selectedRows) === -1)
  1245. {
  1246. for (i = 0; i < this.currentRows.length; i++)
  1247. {
  1248. if (this.currentRows[i][this.identifier] === id)
  1249. {
  1250. selectedRows.push(this.currentRows[i]);
  1251. this.selectedRows.push(id);
  1252. break;
  1253. }
  1254. }
  1255. }
  1256. }
  1257. if (selectedRows.length > 0)
  1258. {
  1259. var selectBoxSelector = getCssSelector(this.options.css.selectBox),
  1260. selectMultiSelectBox = this.selectedRows.length >= this.currentRows.length;
  1261. i = 0;
  1262. while (!this.options.keepSelection && selectMultiSelectBox && i < this.currentRows.length)
  1263. {
  1264. selectMultiSelectBox = ($.inArray(this.currentRows[i++][this.identifier], this.selectedRows) !== -1);
  1265. }
  1266. this.element.find("thead " + selectBoxSelector).prop("checked", selectMultiSelectBox);
  1267. if (!this.options.multiSelect)
  1268. {
  1269. this.element.find("tbody > tr " + selectBoxSelector + ":checked")
  1270. .trigger("click" + namespace);
  1271. }
  1272. for (i = 0; i < this.selectedRows.length; i++)
  1273. {
  1274. this.element.find("tbody > tr[data-row-id=\"" + this.selectedRows[i] + "\"]")
  1275. .addClass(this.options.css.selected)._bgAria("selected", "true")
  1276. .find(selectBoxSelector).prop("checked", true);
  1277. }
  1278. this.element.trigger("selected" + namespace, [selectedRows]);
  1279. }
  1280. }
  1281. return this;
  1282. };
  1283. /**
  1284. * Deselects rows by ids. Deselects all visible rows if no ids are provided.
  1285. * In server-side scenarios only visible rows are deselectable.
  1286. *
  1287. * @method deselect
  1288. * @param [rowsIds] {Array} An array of rows ids to deselect
  1289. * @chainable
  1290. **/
  1291. Grid.prototype.deselect = function(rowIds)
  1292. {
  1293. if (this.selection)
  1294. {
  1295. rowIds = rowIds || this.currentRows.propValues(this.identifier);
  1296. var id, i, pos,
  1297. deselectedRows = [];
  1298. while (rowIds.length > 0)
  1299. {
  1300. id = rowIds.pop();
  1301. pos = $.inArray(id, this.selectedRows);
  1302. if (pos !== -1)
  1303. {
  1304. for (i = 0; i < this.currentRows.length; i++)
  1305. {
  1306. if (this.currentRows[i][this.identifier] === id)
  1307. {
  1308. deselectedRows.push(this.currentRows[i]);
  1309. this.selectedRows.splice(pos, 1);
  1310. break;
  1311. }
  1312. }
  1313. }
  1314. }
  1315. if (deselectedRows.length > 0)
  1316. {
  1317. var selectBoxSelector = getCssSelector(this.options.css.selectBox);
  1318. this.element.find("thead " + selectBoxSelector).prop("checked", false);
  1319. for (i = 0; i < deselectedRows.length; i++)
  1320. {
  1321. this.element.find("tbody > tr[data-row-id=\"" + deselectedRows[i][this.identifier] + "\"]")
  1322. .removeClass(this.options.css.selected)._bgAria("selected", "false")
  1323. .find(selectBoxSelector).prop("checked", false);
  1324. }
  1325. this.element.trigger("deselected" + namespace, [deselectedRows]);
  1326. }
  1327. }
  1328. return this;
  1329. };
  1330. /**
  1331. * Sorts rows.
  1332. *
  1333. * @method sort
  1334. * @param dictionary {Object} A dictionary which contains the sort information
  1335. * @chainable
  1336. **/
  1337. Grid.prototype.sort = function(dictionary)
  1338. {
  1339. var values = (dictionary) ? $.extend({}, dictionary) : {};
  1340. if (values === this.sort)
  1341. {
  1342. return this;
  1343. }
  1344. this.sort = values;
  1345. renderTableHeader.call(this);
  1346. sortRows.call(this);
  1347. loadData.call(this);
  1348. return this;
  1349. };
  1350. // GRID COMMON TYPE EXTENSIONS
  1351. // ============
  1352. $.fn.extend({
  1353. _bgAria: function (name, value)
  1354. {
  1355. return this.attr("aria-" + name, value);
  1356. },
  1357. _bgBusyAria: function(busy)
  1358. {
  1359. return (busy == null || busy) ?
  1360. this._bgAria("busy", "true") :
  1361. this._bgAria("busy", "false");
  1362. },
  1363. _bgRemoveAria: function (name)
  1364. {
  1365. return this.removeAttr("aria-" + name);
  1366. },
  1367. _bgEnableAria: function (enable)
  1368. {
  1369. return (enable == null || enable) ?
  1370. this.removeClass("disabled")._bgAria("disabled", "false") :
  1371. this.addClass("disabled")._bgAria("disabled", "true");
  1372. },
  1373. _bgEnableField: function (enable)
  1374. {
  1375. return (enable == null || enable) ?
  1376. this.removeAttr("disabled") :
  1377. this.attr("disabled", "disable");
  1378. },
  1379. _bgShowAria: function (show)
  1380. {
  1381. return (show == null || show) ?
  1382. this.show()._bgAria("hidden", "false") :
  1383. this.hide()._bgAria("hidden", "true");
  1384. },
  1385. _bgSelectAria: function (select)
  1386. {
  1387. return (select == null || select) ?
  1388. this.addClass("active")._bgAria("selected", "true") :
  1389. this.removeClass("active")._bgAria("selected", "false");
  1390. },
  1391. _bgId: function (id)
  1392. {
  1393. return (id) ? this.attr("id", id) : this.attr("id");
  1394. }
  1395. });
  1396. if (!String.prototype.resolve)
  1397. {
  1398. var formatter = {
  1399. "checked": function(value)
  1400. {
  1401. if (typeof value === "boolean")
  1402. {
  1403. return (value) ? "checked=\"checked\"" : "";
  1404. }
  1405. return value;
  1406. }
  1407. };
  1408. String.prototype.resolve = function (substitutes, prefixes)
  1409. {
  1410. var result = this;
  1411. $.each(substitutes, function (key, value)
  1412. {
  1413. if (value != null && typeof value !== "function")
  1414. {
  1415. if (typeof value === "object")
  1416. {
  1417. var keys = (prefixes) ? $.extend([], prefixes) : [];
  1418. keys.push(key);
  1419. result = result.resolve(value, keys) + "";
  1420. }
  1421. else
  1422. {
  1423. if (formatter && formatter[key] && typeof formatter[key] === "function")
  1424. {
  1425. value = formatter[key](value);
  1426. }
  1427. key = (prefixes) ? prefixes.join(".") + "." + key : key;
  1428. var pattern = new RegExp("\\{\\{" + key + "\\}\\}", "gm");
  1429. result = result.replace(pattern, (value.replace) ? value.replace(/\$/gi, "&#36;") : value);
  1430. }
  1431. }
  1432. });
  1433. return result;
  1434. };
  1435. }
  1436. if (!Array.prototype.first)
  1437. {
  1438. Array.prototype.first = function (condition)
  1439. {
  1440. for (var i = 0; i < this.length; i++)
  1441. {
  1442. var item = this[i];
  1443. if (condition(item))
  1444. {
  1445. return item;
  1446. }
  1447. }
  1448. return null;
  1449. };
  1450. }
  1451. if (!Array.prototype.contains)
  1452. {
  1453. Array.prototype.contains = function (condition)
  1454. {
  1455. for (var i = 0; i < this.length; i++)
  1456. {
  1457. var item = this[i];
  1458. if (condition(item))
  1459. {
  1460. return true;
  1461. }
  1462. }
  1463. return false;
  1464. };
  1465. }
  1466. if (!Array.prototype.page)
  1467. {
  1468. Array.prototype.page = function (page, size)
  1469. {
  1470. var skip = (page - 1) * size,
  1471. end = skip + size;
  1472. return (this.length > skip) ?
  1473. (this.length > end) ? this.slice(skip, end) :
  1474. this.slice(skip) : [];
  1475. };
  1476. }
  1477. if (!Array.prototype.where)
  1478. {
  1479. Array.prototype.where = function (condition)
  1480. {
  1481. var result = [];
  1482. for (var i = 0; i < this.length; i++)
  1483. {
  1484. var item = this[i];
  1485. if (condition(item))
  1486. {
  1487. result.push(item);
  1488. }
  1489. }
  1490. return result;
  1491. };
  1492. }
  1493. if (!Array.prototype.propValues)
  1494. {
  1495. Array.prototype.propValues = function (propName)
  1496. {
  1497. var result = [];
  1498. for (var i = 0; i < this.length; i++)
  1499. {
  1500. result.push(this[i][propName]);
  1501. }
  1502. return result;
  1503. };
  1504. }
  1505. // GRID PLUGIN DEFINITION
  1506. // =====================
  1507. var old = $.fn.bootgrid;
  1508. $.fn.bootgrid = function (option)
  1509. {
  1510. var args = Array.prototype.slice.call(arguments, 1);
  1511. return this.each(function ()
  1512. {
  1513. var $this = $(this),
  1514. instance = $this.data(namespace),
  1515. options = typeof option === "object" && option;
  1516. if (!instance && option === "destroy")
  1517. {
  1518. return;
  1519. }
  1520. if (!instance)
  1521. {
  1522. $this.data(namespace, (instance = new Grid(this, options)));
  1523. init.call(instance);
  1524. }
  1525. if (typeof option === "string")
  1526. {
  1527. return instance[option].apply(instance, args);
  1528. }
  1529. });
  1530. };
  1531. $.fn.bootgrid.Constructor = Grid;
  1532. // GRID NO CONFLICT
  1533. // ===============
  1534. $.fn.bootgrid.noConflict = function ()
  1535. {
  1536. $.fn.bootgrid = old;
  1537. return this;
  1538. };
  1539. // GRID DATA-API
  1540. // ============
  1541. $("[data-toggle=\"bootgrid\"]").bootgrid();
  1542. })(jQuery, window);