PageRenderTime 62ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/backgrid.js

https://github.com/antonyraj/backgrid
JavaScript | 2531 lines | 1117 code | 328 blank | 1086 comment | 238 complexity | 39f78fb6e0e210d7c7dcd6173e5cbdf1 MD5 | raw file
Possible License(s): MIT
  1. /*
  2. backgrid
  3. http://github.com/wyuenho/backgrid
  4. Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors
  5. Licensed under the MIT @license.
  6. */
  7. (function (root, $, _, Backbone) {
  8. "use strict";
  9. /*
  10. backgrid
  11. http://github.com/wyuenho/backgrid
  12. Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors
  13. Licensed under the MIT @license.
  14. */
  15. var window = root;
  16. // Copyright 2009, 2010 Kristopher Michael Kowal
  17. // https://github.com/kriskowal/es5-shim
  18. // ES5 15.5.4.20
  19. // http://es5.github.com/#x15.5.4.20
  20. var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" +
  21. "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" +
  22. "\u2029\uFEFF";
  23. if (!String.prototype.trim || ws.trim()) {
  24. // http://blog.stevenlevithan.com/archives/faster-trim-javascript
  25. // http://perfectionkills.com/whitespace-deviations/
  26. ws = "[" + ws + "]";
  27. var trimBeginRegexp = new RegExp("^" + ws + ws + "*"),
  28. trimEndRegexp = new RegExp(ws + ws + "*$");
  29. String.prototype.trim = function trim() {
  30. if (this === undefined || this === null) {
  31. throw new TypeError("can't convert " + this + " to object");
  32. }
  33. return String(this)
  34. .replace(trimBeginRegexp, "")
  35. .replace(trimEndRegexp, "");
  36. };
  37. }
  38. function capitalize(s) {
  39. return String.fromCharCode(s.charCodeAt(0) - 32) + s.slice(1);
  40. }
  41. function lpad(str, length, padstr) {
  42. var paddingLen = length - (str + '').length;
  43. paddingLen = paddingLen < 0 ? 0 : paddingLen;
  44. var padding = '';
  45. for (var i = 0; i < paddingLen; i++) {
  46. padding = padding + padstr;
  47. }
  48. return padding + str;
  49. }
  50. var Backgrid = root.Backgrid = {
  51. VERSION: "0.2.6",
  52. Extension: {},
  53. requireOptions: function (options, requireOptionKeys) {
  54. for (var i = 0; i < requireOptionKeys.length; i++) {
  55. var key = requireOptionKeys[i];
  56. if (_.isUndefined(options[key])) {
  57. throw new TypeError("'" + key + "' is required");
  58. }
  59. }
  60. },
  61. resolveNameToClass: function (name, suffix) {
  62. if (_.isString(name)) {
  63. var key = _.map(name.split('-'), function (e) { return capitalize(e); }).join('') + suffix;
  64. var klass = Backgrid[key] || Backgrid.Extension[key];
  65. if (_.isUndefined(klass)) {
  66. throw new ReferenceError("Class '" + key + "' not found");
  67. }
  68. return klass;
  69. }
  70. return name;
  71. }
  72. };
  73. _.extend(Backgrid, Backbone.Events);
  74. /**
  75. Command translates a DOM Event into commands that Backgrid
  76. recognizes. Interested parties can listen on selected Backgrid events that
  77. come with an instance of this class and act on the commands.
  78. It is also possible to globally rebind the keyboard shortcuts by replacing
  79. the methods in this class' prototype.
  80. @class Backgrid.Command
  81. @constructor
  82. */
  83. var Command = Backgrid.Command = function (evt) {
  84. _.extend(this, {
  85. altKey: !!evt.altKey,
  86. char: evt.char,
  87. charCode: evt.charCode,
  88. ctrlKey: !!evt.ctrlKey,
  89. key: evt.key,
  90. keyCode: evt.keyCode,
  91. locale: evt.locale,
  92. location: evt.location,
  93. metaKey: !!evt.metaKey,
  94. repeat: !!evt.repeat,
  95. shiftKey: !!evt.shiftKey,
  96. which: evt.which
  97. });
  98. };
  99. _.extend(Command.prototype, {
  100. /**
  101. Up Arrow
  102. @member Backgrid.Command
  103. */
  104. moveUp: function () { return this.keyCode == 38; },
  105. /**
  106. Down Arrow
  107. @member Backgrid.Command
  108. */
  109. moveDown: function () { return this.keyCode === 40; },
  110. /**
  111. Shift Tab
  112. @member Backgrid.Command
  113. */
  114. moveLeft: function () { return this.shiftKey && this.keyCode === 9; },
  115. /**
  116. Tab
  117. @member Backgrid.Command
  118. */
  119. moveRight: function () { return !this.shiftKey && this.keyCode === 9; },
  120. /**
  121. Enter
  122. @member Backgrid.Command
  123. */
  124. save: function () { return this.keyCode === 13; },
  125. /**
  126. Esc
  127. @member Backgrid.Command
  128. */
  129. cancel: function () { return this.keyCode === 27; },
  130. /**
  131. None of the above.
  132. @member Backgrid.Command
  133. */
  134. passThru: function () {
  135. return !(this.moveUp() || this.moveDown() || this.moveLeft() ||
  136. this.moveRight() || this.save() || this.cancel());
  137. }
  138. });
  139. /*
  140. backgrid
  141. http://github.com/wyuenho/backgrid
  142. Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors
  143. Licensed under the MIT @license.
  144. */
  145. /**
  146. Just a convenient class for interested parties to subclass.
  147. The default Cell classes don't require the formatter to be a subclass of
  148. Formatter as long as the fromRaw(rawData) and toRaw(formattedData) methods
  149. are defined.
  150. @abstract
  151. @class Backgrid.CellFormatter
  152. @constructor
  153. */
  154. var CellFormatter = Backgrid.CellFormatter = function () {};
  155. _.extend(CellFormatter.prototype, {
  156. /**
  157. Takes a raw value from a model and returns an optionally formatted string
  158. for display. The default implementation simply returns the supplied value
  159. as is without any type conversion.
  160. @member Backgrid.CellFormatter
  161. @param {*} rawData
  162. @return {*}
  163. */
  164. fromRaw: function (rawData) {
  165. return rawData;
  166. },
  167. /**
  168. Takes a formatted string, usually from user input, and returns a
  169. appropriately typed value for persistence in the model.
  170. If the user input is invalid or unable to be converted to a raw value
  171. suitable for persistence in the model, toRaw must return `undefined`.
  172. @member Backgrid.CellFormatter
  173. @param {string} formattedData
  174. @return {*|undefined}
  175. */
  176. toRaw: function (formattedData) {
  177. return formattedData;
  178. }
  179. });
  180. /**
  181. A floating point number formatter. Doesn't understand notation at the moment.
  182. @class Backgrid.NumberFormatter
  183. @extends Backgrid.CellFormatter
  184. @constructor
  185. @throws {RangeError} If decimals < 0 or > 20.
  186. */
  187. var NumberFormatter = Backgrid.NumberFormatter = function (options) {
  188. options = options ? _.clone(options) : {};
  189. _.extend(this, this.defaults, options);
  190. if (this.decimals < 0 || this.decimals > 20) {
  191. throw new RangeError("decimals must be between 0 and 20");
  192. }
  193. };
  194. NumberFormatter.prototype = new CellFormatter();
  195. _.extend(NumberFormatter.prototype, {
  196. /**
  197. @member Backgrid.NumberFormatter
  198. @cfg {Object} options
  199. @cfg {number} [options.decimals=2] Number of decimals to display. Must be an integer.
  200. @cfg {string} [options.decimalSeparator='.'] The separator to use when
  201. displaying decimals.
  202. @cfg {string} [options.orderSeparator=','] The separator to use to
  203. separator thousands. May be an empty string.
  204. */
  205. defaults: {
  206. decimals: 2,
  207. decimalSeparator: '.',
  208. orderSeparator: ','
  209. },
  210. HUMANIZED_NUM_RE: /(\d)(?=(?:\d{3})+$)/g,
  211. /**
  212. Takes a floating point number and convert it to a formatted string where
  213. every thousand is separated by `orderSeparator`, with a `decimal` number of
  214. decimals separated by `decimalSeparator`. The number returned is rounded
  215. the usual way.
  216. @member Backgrid.NumberFormatter
  217. @param {number} number
  218. @return {string}
  219. */
  220. fromRaw: function (number) {
  221. if (_.isNull(number) || _.isUndefined(number)) return '';
  222. number = number.toFixed(~~this.decimals);
  223. var parts = number.split('.');
  224. var integerPart = parts[0];
  225. var decimalPart = parts[1] ? (this.decimalSeparator || '.') + parts[1] : '';
  226. return integerPart.replace(this.HUMANIZED_NUM_RE, '$1' + this.orderSeparator) + decimalPart;
  227. },
  228. /**
  229. Takes a string, possibly formatted with `orderSeparator` and/or
  230. `decimalSeparator`, and convert it back to a number.
  231. @member Backgrid.NumberFormatter
  232. @param {string} formattedData
  233. @return {number|undefined} Undefined if the string cannot be converted to
  234. a number.
  235. */
  236. toRaw: function (formattedData) {
  237. var rawData = '';
  238. var thousands = formattedData.trim().split(this.orderSeparator);
  239. for (var i = 0; i < thousands.length; i++) {
  240. rawData += thousands[i];
  241. }
  242. var decimalParts = rawData.split(this.decimalSeparator);
  243. rawData = '';
  244. for (var i = 0; i < decimalParts.length; i++) {
  245. rawData = rawData + decimalParts[i] + '.';
  246. }
  247. if (rawData[rawData.length - 1] === '.') {
  248. rawData = rawData.slice(0, rawData.length - 1);
  249. }
  250. var result = (rawData * 1).toFixed(~~this.decimals) * 1;
  251. if (_.isNumber(result) && !_.isNaN(result)) return result;
  252. }
  253. });
  254. /**
  255. Formatter to converts between various datetime formats.
  256. This class only understands ISO-8601 formatted datetime strings and UNIX
  257. offset (number of milliseconds since UNIX Epoch). See
  258. Backgrid.Extension.MomentFormatter if you need a much more flexible datetime
  259. formatter.
  260. @class Backgrid.DatetimeFormatter
  261. @extends Backgrid.CellFormatter
  262. @constructor
  263. @throws {Error} If both `includeDate` and `includeTime` are false.
  264. */
  265. var DatetimeFormatter = Backgrid.DatetimeFormatter = function (options) {
  266. options = options ? _.clone(options) : {};
  267. _.extend(this, this.defaults, options);
  268. if (!this.includeDate && !this.includeTime) {
  269. throw new Error("Either includeDate or includeTime must be true");
  270. }
  271. };
  272. DatetimeFormatter.prototype = new CellFormatter();
  273. _.extend(DatetimeFormatter.prototype, {
  274. /**
  275. @member Backgrid.DatetimeFormatter
  276. @cfg {Object} options
  277. @cfg {boolean} [options.includeDate=true] Whether the values include the
  278. date part.
  279. @cfg {boolean} [options.includeTime=true] Whether the values include the
  280. time part.
  281. @cfg {boolean} [options.includeMilli=false] If `includeTime` is true,
  282. whether to include the millisecond part, if it exists.
  283. */
  284. defaults: {
  285. includeDate: true,
  286. includeTime: true,
  287. includeMilli: false
  288. },
  289. DATE_RE: /^([+\-]?\d{4})-(\d{2})-(\d{2})$/,
  290. TIME_RE: /^(\d{2}):(\d{2}):(\d{2})(\.(\d{3}))?$/,
  291. ISO_SPLITTER_RE: /T|Z| +/,
  292. _convert: function (data, validate) {
  293. var date, time = null;
  294. if (_.isNumber(data)) {
  295. var jsDate = new Date(data);
  296. date = lpad(jsDate.getUTCFullYear(), 4, 0) + '-' + lpad(jsDate.getUTCMonth() + 1, 2, 0) + '-' + lpad(jsDate.getUTCDate(), 2, 0);
  297. time = lpad(jsDate.getUTCHours(), 2, 0) + ':' + lpad(jsDate.getUTCMinutes(), 2, 0) + ':' + lpad(jsDate.getUTCSeconds(), 2, 0);
  298. }
  299. else {
  300. data = data.trim();
  301. var parts = data.split(this.ISO_SPLITTER_RE) || [];
  302. date = this.DATE_RE.test(parts[0]) ? parts[0] : '';
  303. time = date && parts[1] ? parts[1] : this.TIME_RE.test(parts[0]) ? parts[0] : '';
  304. }
  305. var YYYYMMDD = this.DATE_RE.exec(date) || [];
  306. var HHmmssSSS = this.TIME_RE.exec(time) || [];
  307. if (validate) {
  308. if (this.includeDate && _.isUndefined(YYYYMMDD[0])) return;
  309. if (this.includeTime && _.isUndefined(HHmmssSSS[0])) return;
  310. if (!this.includeDate && date) return;
  311. if (!this.includeTime && time) return;
  312. }
  313. var jsDate = new Date(Date.UTC(YYYYMMDD[1] * 1 || 0,
  314. YYYYMMDD[2] * 1 - 1 || 0,
  315. YYYYMMDD[3] * 1 || 0,
  316. HHmmssSSS[1] * 1 || null,
  317. HHmmssSSS[2] * 1 || null,
  318. HHmmssSSS[3] * 1 || null,
  319. HHmmssSSS[5] * 1 || null));
  320. var result = '';
  321. if (this.includeDate) {
  322. result = lpad(jsDate.getUTCFullYear(), 4, 0) + '-' + lpad(jsDate.getUTCMonth() + 1, 2, 0) + '-' + lpad(jsDate.getUTCDate(), 2, 0);
  323. }
  324. if (this.includeTime) {
  325. result = result + (this.includeDate ? 'T' : '') + lpad(jsDate.getUTCHours(), 2, 0) + ':' + lpad(jsDate.getUTCMinutes(), 2, 0) + ':' + lpad(jsDate.getUTCSeconds(), 2, 0);
  326. if (this.includeMilli) {
  327. result = result + '.' + lpad(jsDate.getUTCMilliseconds(), 3, 0);
  328. }
  329. }
  330. if (this.includeDate && this.includeTime) {
  331. result += "Z";
  332. }
  333. return result;
  334. },
  335. /**
  336. Converts an ISO-8601 formatted datetime string to a datetime string, date
  337. string or a time string. The timezone is ignored if supplied.
  338. @member Backgrid.DatetimeFormatter
  339. @param {string} rawData
  340. @return {string|null|undefined} ISO-8601 string in UTC. Null and undefined
  341. values are returned as is.
  342. */
  343. fromRaw: function (rawData) {
  344. if (_.isNull(rawData) || _.isUndefined(rawData)) return '';
  345. return this._convert(rawData);
  346. },
  347. /**
  348. Converts an ISO-8601 formatted datetime string to a datetime string, date
  349. string or a time string. The timezone is ignored if supplied. This method
  350. parses the input values exactly the same way as
  351. Backgrid.Extension.MomentFormatter#fromRaw(), in addition to doing some
  352. sanity checks.
  353. @member Backgrid.DatetimeFormatter
  354. @param {string} formattedData
  355. @return {string|undefined} ISO-8601 string in UTC. Undefined if a date is
  356. found when `includeDate` is false, or a time is found when `includeTime` is
  357. false, or if `includeDate` is true and a date is not found, or if
  358. `includeTime` is true and a time is not found.
  359. */
  360. toRaw: function (formattedData) {
  361. return this._convert(formattedData, true);
  362. }
  363. });
  364. /**
  365. Formatter to convert any value to string.
  366. @class Backgrid.StringFormatter
  367. @extends Backgrid.CellFormatter
  368. @constructor
  369. */
  370. var StringFormatter = Backgrid.StringFormatter = function () {};
  371. StringFormatter.prototype = new CellFormatter();
  372. _.extend(StringFormatter.prototype, {
  373. /**
  374. Converts any value to a string using Ecmascript's implicit type
  375. conversion. If the given value is `null` or `undefined`, an empty string is
  376. returned instead.
  377. @member Backgrid.StringFormatter
  378. @param {*} rawValue
  379. @return {string}
  380. */
  381. fromRaw: function (rawValue) {
  382. if (_.isUndefined(rawValue) || _.isNull(rawValue)) return '';
  383. return rawValue + '';
  384. }
  385. });
  386. /**
  387. Simple email validation formatter.
  388. @class Backgrid.EmailFormatter
  389. @extends Backgrid.CellFormatter
  390. @constructor
  391. */
  392. var EmailFormatter = Backgrid.EmailFormatter = function () {};
  393. EmailFormatter.prototype = new CellFormatter();
  394. _.extend(EmailFormatter.prototype, {
  395. /**
  396. Return the input if it is a string that contains an '@' character and if
  397. the strings before and after '@' are non-empty. If the input does not
  398. validate, `undefined` is returned.
  399. @member Backgrid.EmailFormatter
  400. @param {*} formattedData
  401. @return {string|undefined}
  402. */
  403. toRaw: function (formattedData) {
  404. var parts = formattedData.trim().split("@");
  405. if (parts.length === 2 && _.all(parts)) {
  406. return formattedData;
  407. }
  408. }
  409. });
  410. /**
  411. Formatter for SelectCell.
  412. @class Backgrid.SelectFormatter
  413. @extends Backgrid.CellFormatter
  414. @constructor
  415. */
  416. var SelectFormatter = Backgrid.SelectFormatter = function () {};
  417. SelectFormatter.prototype = new CellFormatter();
  418. _.extend(SelectFormatter.prototype, {
  419. /**
  420. Normalizes raw scalar or array values to an array.
  421. @member Backgrid.SelectFormatter
  422. @param {*} rawValue
  423. @return {Array.<*>}
  424. */
  425. fromRaw: function (rawValue) {
  426. return _.isArray(rawValue) ? rawValue : rawValue != null ? [rawValue] : [];
  427. }
  428. });
  429. /*
  430. backgrid
  431. http://github.com/wyuenho/backgrid
  432. Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors
  433. Licensed under the MIT @license.
  434. */
  435. /**
  436. Generic cell editor base class. Only defines an initializer for a number of
  437. required parameters.
  438. @abstract
  439. @class Backgrid.CellEditor
  440. @extends Backbone.View
  441. */
  442. var CellEditor = Backgrid.CellEditor = Backbone.View.extend({
  443. /**
  444. Initializer.
  445. @param {Object} options
  446. @param {Backgrid.CellFormatter} options.formatter
  447. @param {Backgrid.Column} options.column
  448. @param {Backbone.Model} options.model
  449. @throws {TypeError} If `formatter` is not a formatter instance, or when
  450. `model` or `column` are undefined.
  451. */
  452. initialize: function (options) {
  453. Backgrid.requireOptions(options, ["formatter", "column", "model"]);
  454. this.formatter = options.formatter;
  455. this.column = options.column;
  456. if (!(this.column instanceof Column)) {
  457. this.column = new Column(this.column);
  458. }
  459. this.listenTo(this.model, "backgrid:editing", this.postRender);
  460. },
  461. /**
  462. Post-rendering setup and initialization. Focuses the cell editor's `el` in
  463. this default implementation. **Should** be called by Cell classes after
  464. calling Backgrid.CellEditor#render.
  465. */
  466. postRender: function (model, column) {
  467. if (column == null || column.get("name") == this.column.get("name")) {
  468. this.$el.focus();
  469. }
  470. return this;
  471. }
  472. });
  473. /**
  474. InputCellEditor the cell editor type used by most core cell types. This cell
  475. editor renders a text input box as its editor. The input will render a
  476. placeholder if the value is empty on supported browsers.
  477. @class Backgrid.InputCellEditor
  478. @extends Backgrid.CellEditor
  479. */
  480. var InputCellEditor = Backgrid.InputCellEditor = CellEditor.extend({
  481. /** @property */
  482. tagName: "input",
  483. /** @property */
  484. attributes: {
  485. type: "text"
  486. },
  487. /** @property */
  488. events: {
  489. "blur": "saveOrCancel",
  490. "keydown": "saveOrCancel"
  491. },
  492. /**
  493. Initializer. Removes this `el` from the DOM when a `done` event is
  494. triggered.
  495. @param {Object} options
  496. @param {Backgrid.CellFormatter} options.formatter
  497. @param {Backgrid.Column} options.column
  498. @param {Backbone.Model} options.model
  499. @param {string} [options.placeholder]
  500. */
  501. initialize: function (options) {
  502. CellEditor.prototype.initialize.apply(this, arguments);
  503. if (options.placeholder) {
  504. this.$el.attr("placeholder", options.placeholder);
  505. }
  506. },
  507. /**
  508. Renders a text input with the cell value formatted for display, if it
  509. exists.
  510. */
  511. render: function () {
  512. this.$el.val(this.formatter.fromRaw(this.model.get(this.column.get("name"))));
  513. return this;
  514. },
  515. /**
  516. If the key pressed is `enter`, `tab`, `up`, or `down`, converts the value
  517. in the editor to a raw value for saving into the model using the formatter.
  518. If the key pressed is `esc` the changes are undone.
  519. If the editor goes out of focus (`blur`) but the value is invalid, the
  520. event is intercepted and cancelled so the cell remains in focus pending for
  521. further action. The changes are saved otherwise.
  522. Triggers a Backbone `backgrid:edited` event from the model when successful,
  523. and `backgrid:error` if the value cannot be converted. Classes listening to
  524. the `error` event, usually the Cell classes, should respond appropriately,
  525. usually by rendering some kind of error feedback.
  526. @param {Event} e
  527. */
  528. saveOrCancel: function (e) {
  529. var formatter = this.formatter;
  530. var model = this.model;
  531. var column = this.column;
  532. var command = new Command(e);
  533. var blurred = e.type === "blur";
  534. if (command.moveUp() || command.moveDown() || command.moveLeft() || command.moveRight() ||
  535. command.save() || blurred) {
  536. e.preventDefault();
  537. e.stopPropagation();
  538. var val = this.$el.val();
  539. var newValue = formatter.toRaw(val);
  540. if (_.isUndefined(newValue)) {
  541. model.trigger("backgrid:error", model, column, val);
  542. }
  543. else {
  544. model.set(column.get("name"), newValue);
  545. model.trigger("backgrid:edited", model, column, command);
  546. }
  547. }
  548. // esc
  549. else if (command.cancel()) {
  550. // undo
  551. e.stopPropagation();
  552. model.trigger("backgrid:edited", model, column, command);
  553. }
  554. },
  555. postRender: function (model, column) {
  556. if (column == null || column.get("name") == this.column.get("name")) {
  557. // move the cursor to the end on firefox if text is right aligned
  558. if (this.$el.css("text-align") === "right") {
  559. var val = this.$el.val();
  560. this.$el.focus().val(null).val(val);
  561. }
  562. else this.$el.focus();
  563. }
  564. return this;
  565. }
  566. });
  567. /**
  568. The super-class for all Cell types. By default, this class renders a plain
  569. table cell with the model value converted to a string using the
  570. formatter. The table cell is clickable, upon which the cell will go into
  571. editor mode, which is rendered by a Backgrid.InputCellEditor instance by
  572. default. Upon encountering any formatting errors, this class will add an
  573. `error` CSS class to the table cell.
  574. @abstract
  575. @class Backgrid.Cell
  576. @extends Backbone.View
  577. */
  578. var Cell = Backgrid.Cell = Backbone.View.extend({
  579. /** @property */
  580. tagName: "td",
  581. /**
  582. @property {Backgrid.CellFormatter|Object|string} [formatter=new CellFormatter()]
  583. */
  584. formatter: new CellFormatter(),
  585. /**
  586. @property {Backgrid.CellEditor} [editor=Backgrid.InputCellEditor] The
  587. default editor for all cell instances of this class. This value must be a
  588. class, it will be automatically instantiated upon entering edit mode.
  589. See Backgrid.CellEditor
  590. */
  591. editor: InputCellEditor,
  592. /** @property */
  593. events: {
  594. "click": "enterEditMode"
  595. },
  596. /**
  597. Initializer.
  598. @param {Object} options
  599. @param {Backbone.Model} options.model
  600. @param {Backgrid.Column} options.column
  601. @throws {ReferenceError} If formatter is a string but a formatter class of
  602. said name cannot be found in the Backgrid module.
  603. */
  604. initialize: function (options) {
  605. Backgrid.requireOptions(options, ["model", "column"]);
  606. this.column = options.column;
  607. if (!(this.column instanceof Column)) {
  608. this.column = new Column(this.column);
  609. }
  610. this.formatter = Backgrid.resolveNameToClass(this.column.get("formatter") || this.formatter, "Formatter");
  611. this.editor = Backgrid.resolveNameToClass(this.editor, "CellEditor");
  612. this.listenTo(this.model, "change:" + this.column.get("name"), function () {
  613. if (!this.$el.hasClass("editor")) this.render();
  614. });
  615. this.listenTo(this.model, "backgrid:error", this.renderError);
  616. },
  617. /**
  618. Render a text string in a table cell. The text is converted from the
  619. model's raw value for this cell's column.
  620. */
  621. render: function () {
  622. this.$el.empty();
  623. this.$el.text(this.formatter.fromRaw(this.model.get(this.column.get("name"))));
  624. this.delegateEvents();
  625. return this;
  626. },
  627. /**
  628. If this column is editable, a new CellEditor instance is instantiated with
  629. its required parameters. An `editor` CSS class is added to the cell upon
  630. entering edit mode.
  631. This method triggers a Backbone `backgrid:edit` event from the model when
  632. the cell is entering edit mode and an editor instance has been constructed,
  633. but before it is rendered and inserted into the DOM. The cell and the
  634. constructed cell editor instance are sent as event parameters when this
  635. event is triggered.
  636. When this cell has finished switching to edit mode, a Backbone
  637. `backgrid:editing` event is triggered from the model. The cell and the
  638. constructed cell instance are also sent as parameters in the event.
  639. When the model triggers a `backgrid:error` event, it means the editor is
  640. unable to convert the current user input to an apprpriate value for the
  641. model's column, and an `error` CSS class is added to the cell accordingly.
  642. */
  643. enterEditMode: function () {
  644. var model = this.model;
  645. var column = this.column;
  646. if (column.get("editable")) {
  647. this.currentEditor = new this.editor({
  648. column: this.column,
  649. model: this.model,
  650. formatter: this.formatter
  651. });
  652. model.trigger("backgrid:edit", model, column, this, this.currentEditor);
  653. // Need to redundantly undelegate events for Firefox
  654. this.undelegateEvents();
  655. this.$el.empty();
  656. this.$el.append(this.currentEditor.$el);
  657. this.currentEditor.render();
  658. this.$el.addClass("editor");
  659. model.trigger("backgrid:editing", model, column, this, this.currentEditor);
  660. }
  661. },
  662. /**
  663. Put an `error` CSS class on the table cell.
  664. */
  665. renderError: function (model, column) {
  666. if (column == null || column.get("name") == this.column.get("name")) {
  667. this.$el.addClass("error");
  668. }
  669. },
  670. /**
  671. Removes the editor and re-render in display mode.
  672. */
  673. exitEditMode: function () {
  674. this.$el.removeClass("error");
  675. this.currentEditor.remove();
  676. this.stopListening(this.currentEditor);
  677. delete this.currentEditor;
  678. this.$el.removeClass("editor");
  679. this.render();
  680. },
  681. /**
  682. Clean up this cell.
  683. @chainable
  684. */
  685. remove: function () {
  686. if (this.currentEditor) {
  687. this.currentEditor.remove.apply(this, arguments);
  688. delete this.currentEditor;
  689. }
  690. return Backbone.View.prototype.remove.apply(this, arguments);
  691. }
  692. });
  693. /**
  694. StringCell displays HTML escaped strings and accepts anything typed in.
  695. @class Backgrid.StringCell
  696. @extends Backgrid.Cell
  697. */
  698. var StringCell = Backgrid.StringCell = Cell.extend({
  699. /** @property */
  700. className: "string-cell",
  701. formatter: new StringFormatter()
  702. });
  703. /**
  704. UriCell renders an HTML `<a>` anchor for the value and accepts URIs as user
  705. input values. No type conversion or URL validation is done by the formatter
  706. of this cell. Users who need URL validation are encourage to subclass UriCell
  707. to take advantage of the parsing capabilities of the HTMLAnchorElement
  708. available on HTML5-capable browsers or using a third-party library like
  709. [URI.js](https://github.com/medialize/URI.js).
  710. @class Backgrid.UriCell
  711. @extends Backgrid.Cell
  712. */
  713. var UriCell = Backgrid.UriCell = Cell.extend({
  714. /** @property */
  715. className: "uri-cell",
  716. render: function () {
  717. this.$el.empty();
  718. var formattedValue = this.formatter.fromRaw(this.model.get(this.column.get("name")));
  719. this.$el.append($("<a>", {
  720. tabIndex: -1,
  721. href: formattedValue,
  722. title: formattedValue,
  723. target: "_blank"
  724. }).text(formattedValue));
  725. this.delegateEvents();
  726. return this;
  727. }
  728. });
  729. /**
  730. Like Backgrid.UriCell, EmailCell renders an HTML `<a>` anchor for the
  731. value. The `href` in the anchor is prefixed with `mailto:`. EmailCell will
  732. complain if the user enters a string that doesn't contain the `@` sign.
  733. @class Backgrid.EmailCell
  734. @extends Backgrid.StringCell
  735. */
  736. var EmailCell = Backgrid.EmailCell = StringCell.extend({
  737. /** @property */
  738. className: "email-cell",
  739. formatter: new EmailFormatter(),
  740. render: function () {
  741. this.$el.empty();
  742. var formattedValue = this.formatter.fromRaw(this.model.get(this.column.get("name")));
  743. this.$el.append($("<a>", {
  744. tabIndex: -1,
  745. href: "mailto:" + formattedValue,
  746. title: formattedValue
  747. }).text(formattedValue));
  748. this.delegateEvents();
  749. return this;
  750. }
  751. });
  752. /**
  753. NumberCell is a generic cell that renders all numbers. Numbers are formatted
  754. using a Backgrid.NumberFormatter.
  755. @class Backgrid.NumberCell
  756. @extends Backgrid.Cell
  757. */
  758. var NumberCell = Backgrid.NumberCell = Cell.extend({
  759. /** @property */
  760. className: "number-cell",
  761. /**
  762. @property {number} [decimals=2] Must be an integer.
  763. */
  764. decimals: NumberFormatter.prototype.defaults.decimals,
  765. /** @property {string} [decimalSeparator='.'] */
  766. decimalSeparator: NumberFormatter.prototype.defaults.decimalSeparator,
  767. /** @property {string} [orderSeparator=','] */
  768. orderSeparator: NumberFormatter.prototype.defaults.orderSeparator,
  769. /** @property {Backgrid.CellFormatter} [formatter=Backgrid.NumberFormatter] */
  770. formatter: NumberFormatter,
  771. /**
  772. Initializes this cell and the number formatter.
  773. @param {Object} options
  774. @param {Backbone.Model} options.model
  775. @param {Backgrid.Column} options.column
  776. */
  777. initialize: function (options) {
  778. Cell.prototype.initialize.apply(this, arguments);
  779. this.formatter = new this.formatter({
  780. decimals: this.decimals,
  781. decimalSeparator: this.decimalSeparator,
  782. orderSeparator: this.orderSeparator
  783. });
  784. }
  785. });
  786. /**
  787. An IntegerCell is just a Backgrid.NumberCell with 0 decimals. If a floating
  788. point number is supplied, the number is simply rounded the usual way when
  789. displayed.
  790. @class Backgrid.IntegerCell
  791. @extends Backgrid.NumberCell
  792. */
  793. var IntegerCell = Backgrid.IntegerCell = NumberCell.extend({
  794. /** @property */
  795. className: "integer-cell",
  796. /**
  797. @property {number} decimals Must be an integer.
  798. */
  799. decimals: 0
  800. });
  801. /**
  802. DatetimeCell is a basic cell that accepts datetime string values in RFC-2822
  803. or W3C's subset of ISO-8601 and displays them in ISO-8601 format. For a much
  804. more sophisticated date time cell with better datetime formatting, take a
  805. look at the Backgrid.Extension.MomentCell extension.
  806. @class Backgrid.DatetimeCell
  807. @extends Backgrid.Cell
  808. See:
  809. - Backgrid.Extension.MomentCell
  810. - Backgrid.DatetimeFormatter
  811. */
  812. var DatetimeCell = Backgrid.DatetimeCell = Cell.extend({
  813. /** @property */
  814. className: "datetime-cell",
  815. /**
  816. @property {boolean} [includeDate=true]
  817. */
  818. includeDate: DatetimeFormatter.prototype.defaults.includeDate,
  819. /**
  820. @property {boolean} [includeTime=true]
  821. */
  822. includeTime: DatetimeFormatter.prototype.defaults.includeTime,
  823. /**
  824. @property {boolean} [includeMilli=false]
  825. */
  826. includeMilli: DatetimeFormatter.prototype.defaults.includeMilli,
  827. /** @property {Backgrid.CellFormatter} [formatter=Backgrid.DatetimeFormatter] */
  828. formatter: DatetimeFormatter,
  829. /**
  830. Initializes this cell and the datetime formatter.
  831. @param {Object} options
  832. @param {Backbone.Model} options.model
  833. @param {Backgrid.Column} options.column
  834. */
  835. initialize: function (options) {
  836. Cell.prototype.initialize.apply(this, arguments);
  837. this.formatter = new this.formatter({
  838. includeDate: this.includeDate,
  839. includeTime: this.includeTime,
  840. includeMilli: this.includeMilli
  841. });
  842. var placeholder = this.includeDate ? "YYYY-MM-DD" : "";
  843. placeholder += (this.includeDate && this.includeTime) ? "T" : "";
  844. placeholder += this.includeTime ? "HH:mm:ss" : "";
  845. placeholder += (this.includeTime && this.includeMilli) ? ".SSS" : "";
  846. this.editor = this.editor.extend({
  847. attributes: _.extend({}, this.editor.prototype.attributes, this.editor.attributes, {
  848. placeholder: placeholder
  849. })
  850. });
  851. }
  852. });
  853. /**
  854. DateCell is a Backgrid.DatetimeCell without the time part.
  855. @class Backgrid.DateCell
  856. @extends Backgrid.DatetimeCell
  857. */
  858. var DateCell = Backgrid.DateCell = DatetimeCell.extend({
  859. /** @property */
  860. className: "date-cell",
  861. /** @property */
  862. includeTime: false
  863. });
  864. /**
  865. TimeCell is a Backgrid.DatetimeCell without the date part.
  866. @class Backgrid.TimeCell
  867. @extends Backgrid.DatetimeCell
  868. */
  869. var TimeCell = Backgrid.TimeCell = DatetimeCell.extend({
  870. /** @property */
  871. className: "time-cell",
  872. /** @property */
  873. includeDate: false
  874. });
  875. /**
  876. BooleanCellEditor renders a checkbox as its editor.
  877. @class Backgrid.BooleanCellEditor
  878. @extends Backgrid.CellEditor
  879. */
  880. var BooleanCellEditor = Backgrid.BooleanCellEditor = CellEditor.extend({
  881. /** @property */
  882. tagName: "input",
  883. /** @property */
  884. attributes: {
  885. tabIndex: -1,
  886. type: "checkbox"
  887. },
  888. /** @property */
  889. events: {
  890. "mousedown": function () {
  891. this.mouseDown = true;
  892. },
  893. "blur": "enterOrExitEditMode",
  894. "mouseup": function () {
  895. this.mouseDown = false;
  896. },
  897. "change": "saveOrCancel",
  898. "keydown": "saveOrCancel"
  899. },
  900. /**
  901. Renders a checkbox and check it if the model value of this column is true,
  902. uncheck otherwise.
  903. */
  904. render: function () {
  905. var val = this.formatter.fromRaw(this.model.get(this.column.get("name")));
  906. this.$el.prop("checked", val);
  907. return this;
  908. },
  909. /**
  910. Event handler. Hack to deal with the case where `blur` is fired before
  911. `change` and `click` on a checkbox.
  912. */
  913. enterOrExitEditMode: function (e) {
  914. if (!this.mouseDown) {
  915. var model = this.model;
  916. model.trigger("backgrid:edited", model, this.column, new Command(e));
  917. }
  918. },
  919. /**
  920. Event handler. Save the value into the model if the event is `change` or
  921. one of the keyboard navigation key presses. Exit edit mode without saving
  922. if `escape` was pressed.
  923. */
  924. saveOrCancel: function (e) {
  925. var model = this.model;
  926. var column = this.column;
  927. var formatter = this.formatter;
  928. var command = new Command(e);
  929. // skip ahead to `change` when space is pressed
  930. if (command.passThru() && e.type != "change") return true;
  931. if (command.cancel()) {
  932. e.stopPropagation();
  933. model.trigger("backgrid:edited", model, column, command);
  934. }
  935. var $el = this.$el;
  936. if (command.save() || command.moveLeft() || command.moveRight() || command.moveUp() ||
  937. command.moveDown()) {
  938. e.preventDefault();
  939. e.stopPropagation();
  940. var val = formatter.toRaw($el.prop("checked"));
  941. model.set(column.get("name"), val);
  942. model.trigger("backgrid:edited", model, column, command);
  943. }
  944. else if (e.type == "change") {
  945. var val = formatter.toRaw($el.prop("checked"));
  946. model.set(column.get("name"), val);
  947. $el.focus();
  948. }
  949. }
  950. });
  951. /**
  952. BooleanCell renders a checkbox both during display mode and edit mode. The
  953. checkbox is checked if the model value is true, unchecked otherwise.
  954. @class Backgrid.BooleanCell
  955. @extends Backgrid.Cell
  956. */
  957. var BooleanCell = Backgrid.BooleanCell = Cell.extend({
  958. /** @property */
  959. className: "boolean-cell",
  960. /** @property */
  961. editor: BooleanCellEditor,
  962. /** @property */
  963. events: {
  964. "click": "enterEditMode"
  965. },
  966. /**
  967. Renders a checkbox and check it if the model value of this column is true,
  968. uncheck otherwise.
  969. */
  970. render: function () {
  971. this.$el.empty();
  972. this.$el.append($("<input>", {
  973. tabIndex: -1,
  974. type: "checkbox",
  975. checked: this.formatter.fromRaw(this.model.get(this.column.get("name")))
  976. }));
  977. this.delegateEvents();
  978. return this;
  979. }
  980. });
  981. /**
  982. SelectCellEditor renders an HTML `<select>` fragment as the editor.
  983. @class Backgrid.SelectCellEditor
  984. @extends Backgrid.CellEditor
  985. */
  986. var SelectCellEditor = Backgrid.SelectCellEditor = CellEditor.extend({
  987. /** @property */
  988. tagName: "select",
  989. /** @property */
  990. events: {
  991. "change": "save",
  992. "blur": "close",
  993. "keydown": "close"
  994. },
  995. /** @property {function(Object, ?Object=): string} template */
  996. template: _.template('<option value="<%- value %>" <%= selected ? \'selected="selected"\' : "" %>><%- text %></option>'),
  997. setOptionValues: function (optionValues) {
  998. this.optionValues = optionValues;
  999. },
  1000. setMultiple: function (multiple) {
  1001. this.multiple = multiple;
  1002. this.$el.prop("multiple", multiple);
  1003. },
  1004. _renderOptions: function (nvps, selectedValues) {
  1005. var options = '';
  1006. for (var i = 0; i < nvps.length; i++) {
  1007. options = options + this.template({
  1008. text: nvps[i][0],
  1009. value: nvps[i][1],
  1010. selected: selectedValues.indexOf(nvps[i][1]) > -1
  1011. });
  1012. }
  1013. return options;
  1014. },
  1015. /**
  1016. Renders the options if `optionValues` is a list of name-value pairs. The
  1017. options are contained inside option groups if `optionValues` is a list of
  1018. object hashes. The name is rendered at the option text and the value is the
  1019. option value. If `optionValues` is a function, it is called without a
  1020. parameter.
  1021. */
  1022. render: function () {
  1023. this.$el.empty();
  1024. var optionValues = _.result(this, "optionValues");
  1025. var selectedValues = this.formatter.fromRaw(this.model.get(this.column.get("name")));
  1026. if (!_.isArray(optionValues)) throw TypeError("optionValues must be an array");
  1027. var optionValue = null;
  1028. var optionText = null;
  1029. var optionValue = null;
  1030. var optgroupName = null;
  1031. var optgroup = null;
  1032. for (var i = 0; i < optionValues.length; i++) {
  1033. var optionValue = optionValues[i];
  1034. if (_.isArray(optionValue)) {
  1035. optionText = optionValue[0];
  1036. optionValue = optionValue[1];
  1037. this.$el.append(this.template({
  1038. text: optionText,
  1039. value: optionValue,
  1040. selected: selectedValues.indexOf(optionValue) > -1
  1041. }));
  1042. }
  1043. else if (_.isObject(optionValue)) {
  1044. optgroupName = optionValue.name;
  1045. optgroup = $("<optgroup></optgroup>", { label: optgroupName });
  1046. optgroup.append(this._renderOptions(optionValue.values, selectedValues));
  1047. this.$el.append(optgroup);
  1048. }
  1049. else {
  1050. throw TypeError("optionValues elements must be a name-value pair or an object hash of { name: 'optgroup label', value: [option name-value pairs] }");
  1051. }
  1052. }
  1053. this.delegateEvents();
  1054. return this;
  1055. },
  1056. /**
  1057. Saves the value of the selected option to the model attribute. Triggers a
  1058. `backgrid:edited` Backbone event from the model.
  1059. */
  1060. save: function (e) {
  1061. var model = this.model;
  1062. var column = this.column;
  1063. model.set(column.get("name"), this.formatter.toRaw(this.$el.val()));
  1064. model.trigger("backgrid:edited", model, column, new Command(e));
  1065. },
  1066. /**
  1067. Triggers a `backgrid:edited` event from the model so the body can close
  1068. this editor.
  1069. */
  1070. close: function (e) {
  1071. var model = this.model;
  1072. var column = this.column;
  1073. var command = new Command(e);
  1074. if (command.cancel()) {
  1075. e.stopPropagation();
  1076. model.trigger("backgrid:edited", model, column, new Command(e));
  1077. }
  1078. else if (command.save() || command.moveLeft() || command.moveRight() ||
  1079. command.moveUp() || command.moveDown() || e.type == "blur") {
  1080. e.preventDefault();
  1081. e.stopPropagation();
  1082. if (e.type == "blur" && this.$el.find("option").length === 1) {
  1083. model.set(column.get("name"), this.formatter.toRaw(this.$el.val()));
  1084. }
  1085. model.trigger("backgrid:edited", model, column, new Command(e));
  1086. }
  1087. }
  1088. });
  1089. /**
  1090. SelectCell is also a different kind of cell in that upon going into edit mode
  1091. the cell renders a list of options to pick from, as opposed to an input box.
  1092. SelectCell cannot be referenced by its string name when used in a column
  1093. definition because it requires an `optionValues` class attribute to be
  1094. defined. `optionValues` can either be a list of name-value pairs, to be
  1095. rendered as options, or a list of object hashes which consist of a key *name*
  1096. which is the option group name, and a key *values* which is a list of
  1097. name-value pairs to be rendered as options under that option group.
  1098. In addition, `optionValues` can also be a parameter-less function that
  1099. returns one of the above. If the options are static, it is recommended the
  1100. returned values to be memoized. `_.memoize()` is a good function to help with
  1101. that.
  1102. During display mode, the default formatter will normalize the raw model value
  1103. to an array of values whether the raw model value is a scalar or an
  1104. array. Each value is compared with the `optionValues` values using
  1105. Ecmascript's implicit type conversion rules. When exiting edit mode, no type
  1106. conversion is performed when saving into the model. This behavior is not
  1107. always desirable when the value type is anything other than string. To
  1108. control type conversion on the client-side, you should subclass SelectCell to
  1109. provide a custom formatter or provide the formatter to your column
  1110. definition.
  1111. See:
  1112. [$.fn.val()](http://api.jquery.com/val/)
  1113. @class Backgrid.SelectCell
  1114. @extends Backgrid.Cell
  1115. */
  1116. var SelectCell = Backgrid.SelectCell = Cell.extend({
  1117. /** @property */
  1118. className: "select-cell",
  1119. /** @property */
  1120. editor: SelectCellEditor,
  1121. /** @property */
  1122. multiple: false,
  1123. /** @property */
  1124. formatter: new SelectFormatter(),
  1125. /**
  1126. @property {Array.<Array>|Array.<{name: string, values: Array.<Array>}>} optionValues
  1127. */
  1128. optionValues: undefined,
  1129. /** @property */
  1130. delimiter: ', ',
  1131. /**
  1132. Initializer.
  1133. @param {Object} options
  1134. @param {Backbone.Model} options.model
  1135. @param {Backgrid.Column} options.column
  1136. @throws {TypeError} If `optionsValues` is undefined.
  1137. */
  1138. initialize: function (options) {
  1139. Cell.prototype.initialize.apply(this, arguments);
  1140. Backgrid.requireOptions(this, ["optionValues"]);
  1141. this.listenTo(this.model, "backgrid:edit", function (model, column, cell, editor) {
  1142. if (column.get("name") == this.column.get("name")) {
  1143. editor.setOptionValues(this.optionValues);
  1144. editor.setMultiple(this.multiple);
  1145. }
  1146. });
  1147. },
  1148. /**
  1149. Renders the label using the raw value as key to look up from `optionValues`.
  1150. @throws {TypeError} If `optionValues` is malformed.
  1151. */
  1152. render: function () {
  1153. this.$el.empty();
  1154. var optionValues = this.optionValues;
  1155. var rawData = this.formatter.fromRaw(this.model.get(this.column.get("name")));
  1156. var selectedText = [];
  1157. try {
  1158. if (!_.isArray(optionValues) || _.isEmpty(optionValues)) throw new TypeError;
  1159. for (var k = 0; k < rawData.length; k++) {
  1160. var rawDatum = rawData[k];
  1161. for (var i = 0; i < optionValues.length; i++) {
  1162. var optionValue = optionValues[i];
  1163. if (_.isArray(optionValue)) {
  1164. var optionText = optionValue[0];
  1165. var optionValue = optionValue[1];
  1166. if (optionValue == rawDatum) selectedText.push(optionText);
  1167. }
  1168. else if (_.isObject(optionValue)) {
  1169. var optionGroupValues = optionValue.values;
  1170. for (var j = 0; j < optionGroupValues.length; j++) {
  1171. var optionGroupValue = optionGroupValues[j];
  1172. if (optionGroupValue[1] == rawDatum) {
  1173. selectedText.push(optionGroupValue[0]);
  1174. }
  1175. }
  1176. }
  1177. else {
  1178. throw new TypeError;
  1179. }
  1180. }
  1181. }
  1182. this.$el.append(selectedText.join(this.delimiter));
  1183. }
  1184. catch (ex) {
  1185. if (ex instanceof TypeError) {
  1186. throw TypeError("'optionValues' must be of type {Array.<Array>|Array.<{name: string, values: Array.<Array>}>}");
  1187. }
  1188. throw ex;
  1189. }
  1190. this.delegateEvents();
  1191. return this;
  1192. }
  1193. });
  1194. /*
  1195. backgrid
  1196. http://github.com/wyuenho/backgrid
  1197. Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors
  1198. Licensed under the MIT @license.
  1199. */
  1200. /**
  1201. A Column is a placeholder for column metadata.
  1202. You usually don't need to create an instance of this class yourself as a
  1203. collection of column instances will be created for you from a list of column
  1204. attributes in the Backgrid.js view class constructors.
  1205. @class Backgrid.Column
  1206. @extends Backbone.Model
  1207. */
  1208. var Column = Backgrid.Column = Backbone.Model.extend({
  1209. defaults: {
  1210. name: undefined,
  1211. label: undefined,
  1212. sortable: true,
  1213. editable: true,
  1214. renderable: true,
  1215. formatter: undefined,
  1216. cell: undefined,
  1217. headerCell: undefined
  1218. },
  1219. /**
  1220. Initializes this Column instance.
  1221. @param {Object} attrs Column attributes.
  1222. @param {string} attrs.name The name of the model attribute.
  1223. @param {string|Backgrid.Cell} attrs.cell The cell type.
  1224. If this is a string, the capitalized form will be used to look up a
  1225. cell class in Backbone, i.e.: string => StringCell. If a Cell subclass
  1226. is supplied, it is initialized with a hash of parameters. If a Cell
  1227. instance is supplied, it is used directly.
  1228. @param {string|Backgrid.HeaderCell} [attrs.headerCell] The header cell type.
  1229. @param {string} [attrs.label] The label to show in the header.
  1230. @param {boolean} [attrs.sortable=true]
  1231. @param {boolean} [attrs.editable=true]
  1232. @param {boolean} [attrs.renderable=true]
  1233. @param {Backgrid.CellFormatter|Object|string} [attrs.formatter] The
  1234. formatter to use to convert between raw model values and user input.
  1235. @throws {TypeError} If attrs.cell or attrs.options are not supplied.
  1236. @throws {ReferenceError} If attrs.cell is a string but a cell class of
  1237. said name cannot be found in the Backgrid module.
  1238. See:
  1239. - Backgrid.Cell
  1240. - Backgrid.CellFormatter
  1241. */
  1242. initialize: function (attrs) {
  1243. Backgrid.requireOptions(attrs, ["cell", "name"]);
  1244. if (!this.has("label")) {
  1245. this.set({ label: this.get("name") }, { silent: true });
  1246. }
  1247. var headerCell = Backgrid.resolveNameToClass(this.get("headerCell"), "HeaderCell");
  1248. var cell = Backgrid.resolveNameToClass(this.get("cell"), "Cell");
  1249. this.set({ cell: cell, headerCell: headerCell }, { silent: true });
  1250. }
  1251. });
  1252. /**
  1253. A Backbone collection of Column instances.
  1254. @class Backgrid.Columns
  1255. @extends Backbone.Collection
  1256. */
  1257. var Columns = Backgrid.Columns = Backbone.Collection.extend({
  1258. /**
  1259. @property {Backgrid.Column} model
  1260. */
  1261. model: Column
  1262. });
  1263. /*
  1264. backgrid
  1265. http://github.com/wyuenho/backgrid
  1266. Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors
  1267. Licensed under the MIT @license.
  1268. */
  1269. /**
  1270. Row is a simple container view that takes a model instance and a list of
  1271. column metadata describing how each of the model's attribute is to be
  1272. rendered, and apply the appropriate cell to each attribute.
  1273. @class Backgrid.Row
  1274. @extends Backbone.View
  1275. */
  1276. var Row = Backgrid.Row = Backbone.View.extend({
  1277. /** @property */
  1278. tagName: "tr",
  1279. requiredOptions: ["columns", "model"],
  1280. /**
  1281. Initializes a row view instance.
  1282. @param {Object} options
  1283. @param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata.
  1284. @param {Backbone.Model} options.model The model instance to render.
  1285. @throws {TypeError} If options.columns or options.model is undefined.
  1286. */
  1287. initialize: function (options) {
  1288. Backgrid.requireOptions(options, this.requiredOptions);
  1289. var columns = this.columns = options.columns;
  1290. if (!(columns instanceof Backbone.Collection)) {
  1291. columns = this.columns = new Columns(columns);
  1292. }
  1293. var cells = this.cells = [];
  1294. for (var i = 0; i < columns.length; i++) {
  1295. cells.push(this.makeCell(columns.at(i), options));
  1296. }
  1297. this.listenTo(columns, "change:renderable", function (column, renderable) {
  1298. for (var i = 0; i < cells.length; i++) {
  1299. var cell = cells[i];
  1300. if (cell.column.get("name") == column.get("name")) {
  1301. if (renderable) cell.$el.show(); else cell.$el.hide();
  1302. }
  1303. }
  1304. });
  1305. this.listenTo(columns, "add", function (column, columns) {
  1306. var i = columns.indexOf(column);
  1307. var cell = this.makeCell(column, options);
  1308. cells.splice(i, 0, cell);
  1309. if (!cell.column.get("renderable")) cell.$el.hide();
  1310. var $el = this.$el;
  1311. if (i === 0) {
  1312. $el.prepend(cell.render().$el);
  1313. }
  1314. else if (i === columns.length - 1) {
  1315. $el.append(cell.render().$el);
  1316. }
  1317. else {
  1318. $el.children().eq(i).before(cell.render().$el);
  1319. }
  1320. });
  1321. this.listenTo(columns, "remove", function (column, columns, opts) {
  1322. cells[opts.index].remove();
  1323. cells.splice(opts.index, 1);
  1324. });
  1325. },
  1326. /**
  1327. Factory method for making a cell. Used by #initialize internally. Override
  1328. this to provide an appropriate cell instance for a custom Row subclass.
  1329. @protected
  1330. @param {Backgrid.Column} column
  1331. @param {Object} options The options passed to #initialize.
  1332. @return {Backgrid.Cell}
  1333. */
  1334. makeCell: function (column) {
  1335. return new (column.get("cell"))({
  1336. column: column,
  1337. model: this.model
  1338. });
  1339. },
  1340. /**
  1341. Renders a row of cells for this row's model.
  1342. */
  1343. render: function () {
  1344. this.$el.empty();
  1345. var fragment = document.createDocumentFragment();
  1346. for (var i = 0; i < this.cells.length; i++) {
  1347. var cell = this.cells[i];
  1348. fragment.appendChild(cell.render().el);
  1349. if (!cell.column.get("renderable")) cell.$el.hide();
  1350. }
  1351. this.el.appendChild(fragment);
  1352. this.delegateEvents();
  1353. return this;
  1354. },
  1355. /**
  1356. Clean up this row and its cells.
  1357. @chainable
  1358. */
  1359. remove: function () {
  1360. for (var i = 0; i < this.cells.length; i++) {
  1361. var cell = this.cells[i];
  1362. cell.remove.apply(cell, arguments);
  1363. }
  1364. return Backbone.View.prototype.remove.apply(this, arguments);
  1365. }
  1366. });
  1367. /**
  1368. EmptyRow is a simple container view that takes a list of column and render a
  1369. row with a single column.
  1370. @class Backgrid.EmptyRow
  1371. @extends Backbone.View
  1372. */
  1373. var EmptyRow = Backgrid.EmptyRow = Backbone.View.extend({
  1374. /** @property */
  1375. tagName: "tr",
  1376. /** @property */
  1377. emptyText: null,
  1378. /**
  1379. Initializer.
  1380. @param {Object} options
  1381. @param {string} options.emptyText
  1382. @param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata.
  1383. */
  1384. initialize: function (options) {
  1385. Backgrid.requireOptions(options, ["emptyText", "columns"]);
  1386. this.emptyText = options.emptyText;
  1387. this.columns = options.columns;
  1388. },
  1389. /**
  1390. Renders an empty row.
  1391. */
  1392. render: function () {
  1393. this.$el.empty();
  1394. var td = document.createElement("td");
  1395. td.setAttribute("colspan", this.columns.length);
  1396. td.textContent = this.emptyText;
  1397. this.el.setAttribute("class", "empty");
  1398. this.el.appendChild(td);
  1399. return this;
  1400. }
  1401. });
  1402. /*
  1403. backgrid
  1404. http://github.com/wyuenho/backgrid
  1405. Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors
  1406. Licensed under the MIT @license.
  1407. */
  1408. /**
  1409. HeaderCell is a special cell class that renders a column header cell. If the
  1410. column is sortable, a sorter is also rendered and will trigger a table
  1411. refresh after sorting.
  1412. @class Backgrid.HeaderCell
  1413. @extends Backbone.View
  1414. */
  1415. var HeaderCell = Backgrid.HeaderCell = Backbone.View.extend({
  1416. /** @property */
  1417. tagName: "th",
  1418. /** @property */
  1419. events: {
  1420. "click a": "onClick"
  1421. },
  1422. /**
  1423. @property {null|"ascending"|"descending"} _direction The current sorting
  1424. direction of this column.
  1425. */
  1426. _direction: null,
  1427. /**
  1428. Initializer.
  1429. @param {Object} options
  1430. @param {Backgrid.Column|Object} options.column
  1431. @throws {TypeError} If options.column or options.collection is undefined.
  1432. */
  1433. initialize: function (options) {
  1434. Backgrid.requireOptions(options, ["column", "collection"]);
  1435. this.column = options.column;
  1436. if (!(this.column instanceof Column)) {
  1437. this.column = new Column(this.column);
  1438. }
  1439. this.listenTo(this.collection, "backgrid:sort", this._resetCellDirection);
  1440. },
  1441. /**
  1442. Gets or sets the direction of this cell. If called directly without
  1443. parameters, returns the current direction of this cell, otherwise sets
  1444. it. If a `null` is given, sets this cell back to the default order.
  1445. @param {null|"ascending"|"descending"} dir
  1446. @return {null|string} The current direction or the changed direction.
  1447. */
  1448. direction: function (dir) {
  1449. if (arguments.length) {
  1450. if (this._direction) this.$el.removeClass(this._direction);
  1451. if (dir) this.$el.addClass(dir);
  1452. this._direction = dir;
  1453. }
  1454. return this._direction;
  1455. },
  1456. /**
  1457. Event handler for the Backbone `backgrid:sort` event. Resets this cell's
  1458. direction to default if sorting is being done on another column.
  1459. @private
  1460. */
  1461. _resetCellDirection: function (sortByColName, direction, comparator, collection) {
  1462. if (collection == this.collection) {
  1463. if (sortByColName !== this.column.get("name")) this.direction(null);
  1464. else this.direction(direction);
  1465. }
  1466. },
  1467. /**
  1468. Event handler for the `click` event on the cell's anchor. If the column is
  1469. sortable, clicking on the anchor will cycle through 3 sorting orderings -
  1470. `ascending`, `descending`, and default.
  1471. */
  1472. onClick: function (e) {
  1473. e.preventDefault();
  1474. var columnName = this.column.get("name");
  1475. if (this.column.get("sortable")) {
  1476. if (this.direction() === "ascending") {
  1477. this.sort(columnName, "descending", function (left, right) {
  1478. var leftVal = left.get(columnName);
  1479. var rightVal = right.get(columnName);
  1480. if (leftVal === rightVal) {
  1481. return 0;
  1482. }
  1483. else if (leftVal > rightVal) { return -1; }
  1484. return 1;
  1485. });
  1486. }
  1487. else if (this.direction() === "descending") {
  1488. this.sort(columnName, null);
  1489. }
  1490. else {
  1491. this.sort(columnName, "ascending", function (left, right) {
  1492. var leftVal = left.get(columnName);
  1493. var rightVal = right.get(columnName);
  1494. if (leftVal === rightVal) {
  1495. return 0;
  1496. }
  1497. else if (leftVal < rightVal) { return -1; }
  1498. return 1;
  1499. });
  1500. }
  1501. }
  1502. },
  1503. /**
  1504. If the underlying collection is a Backbone.PageableCollection in
  1505. server-mode or infinite-mode, a page of models is fetched after sorting is
  1506. done on the server.
  1507. If the underlying collection is a Backbone.PageableCollection in
  1508. client-mode, or any
  1509. [Backbone.Collection](http://backbonejs.org/#Collection) instance, sorting
  1510. is done on the client side. If the collection is an instance of a
  1511. Backbone.PageableCollection, sorting will be done globally on all the pages
  1512. and the current page will then be returned.
  1513. Triggers a Backbone `backgrid:sort` event from the collection when done
  1514. with the column name, direction, comparator and a reference to the
  1515. collection.
  1516. @param {string} columnName
  1517. @param {null|"ascending"|"descending"} direction
  1518. @param {function(*, *): number} [comparator]
  1519. See [Backbone.Collection#comparator](http://backbonejs.org/#Collection-comparator)
  1520. */
  1521. sort: function (columnName, direction, comparator) {
  1522. comparator = comparator || this._cidComparator;
  1523. var collection = this.collection;
  1524. if (Backbone.PageableCollection && collection instanceof Backbone.PageableCollection) {
  1525. var order;
  1526. if (direction === "ascending") order = -1;
  1527. else if (direction === "descending") order = 1;
  1528. else order = null;
  1529. collection.setSorting(order ? columnName : null, order);
  1530. if (collection.mode == "client") {
  1531. if (!collection.fullCollection.comparator) {
  1532. collection.fullCollection.comparator = comparator;
  1533. }
  1534. collection.fullCollection.sort();
  1535. }
  1536. else collection.fetch({reset: true});
  1537. }
  1538. else {
  1539. collection.comparator = comparator;
  1540. collection.sort();
  1541. }
  1542. this.collection.trigger("backgrid:sort", columnName, direction, comparator, this.collection);
  1543. },
  1544. /**
  1545. Default comparator for Backbone.Collections. Sorts cids in ascending
  1546. order. The cids of the models are assumed to be in insertion order.
  1547. @private
  1548. @param {*} left
  1549. @param {*} right
  1550. */
  1551. _cidComparator: function (left, right) {
  1552. var lcid = left.cid, rcid = right.cid;
  1553. if (!_.isUndefined(lcid) && !_.isUndefined(rcid)) {
  1554. lcid = lcid.slice(1) * 1, rcid = rcid.slice(1) * 1;
  1555. if (lcid < rcid) return -1;
  1556. else if (lcid > rcid) return 1;
  1557. }
  1558. return 0;
  1559. },
  1560. /**
  1561. Renders a header cell with a sorter and a label.
  1562. */
  1563. render: function () {
  1564. this.$el.empty();
  1565. var $label = $("<a>").text(this.column.get("label")).append("<b class='sort-caret'></b>");
  1566. this.$el.append($label);
  1567. this.delegateEvents();
  1568. return this;
  1569. }
  1570. });
  1571. /**
  1572. HeaderRow is a controller for a row of header cells.
  1573. @class Backgrid.HeaderRow
  1574. @extends Backgrid.Row
  1575. */
  1576. var HeaderRow = Backgrid.HeaderRow = Backgrid.Row.extend({
  1577. requiredOptions: ["columns", "collection"],
  1578. /**
  1579. Initializer.
  1580. @param {Object} options
  1581. @param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns
  1582. @param {Backgrid.HeaderCell} [options.headerCell] Customized default
  1583. HeaderCell for all the columns. Supply a HeaderCell class or instance to a
  1584. the `headerCell` key in a column definition for column-specific header
  1585. rendering.
  1586. @throws {TypeError} If options.columns or options.collection is undefined.
  1587. */
  1588. initialize: function () {
  1589. Backgrid.Row.prototype.initialize.apply(this, arguments);
  1590. },
  1591. makeCell: function (column, options) {
  1592. var headerCell = column.get("headerCell") || options.headerCell || HeaderCell;
  1593. headerCell = new headerCell({
  1594. column: column,
  1595. collection: this.collection
  1596. });
  1597. return headerCell;
  1598. }
  1599. });
  1600. /**
  1601. Header is a special structural view class that renders a table head with a
  1602. single row of header cells.
  1603. @class Backgrid.Header
  1604. @extends Backbone.View
  1605. */
  1606. var Header = Backgrid.Header = Backbone.View.extend({
  1607. /** @property */
  1608. tagName: "thead",
  1609. /**
  1610. Initializer. Initializes this table head view to contain a single header
  1611. row view.
  1612. @param {Object} options
  1613. @param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata.
  1614. @param {Backbone.Model} options.model The model instance to render.
  1615. @throws {TypeError} If options.columns or options.model is undefined.
  1616. */
  1617. initialize: function (options) {
  1618. Backgrid.requireOptions(options, ["columns", "collection"]);
  1619. this.columns = options.columns;
  1620. if (!(this.columns instanceof Backbone.Collection)) {
  1621. this.columns = new Columns(this.columns);
  1622. }
  1623. this.row = new Backgrid.HeaderRow({
  1624. columns: this.columns,
  1625. collection: this.collection
  1626. });
  1627. },
  1628. /**
  1629. Renders this table head with a single row of header cells.
  1630. */
  1631. render: function () {
  1632. this.$el.append(this.row.render().$el);
  1633. this.delegateEvents();
  1634. return this;
  1635. },
  1636. /**
  1637. Clean up this header and its row.
  1638. @chainable
  1639. */
  1640. remove: function () {
  1641. this.row.remove.apply(this.row, arguments);
  1642. return Backbone.View.prototype.remove.apply(this, arguments);
  1643. }
  1644. });
  1645. /*
  1646. backgrid
  1647. http://github.com/wyuenho/backgrid
  1648. Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors
  1649. Licensed under the MIT @license.
  1650. */
  1651. /**
  1652. Body is the table body which contains the rows inside a table. Body is
  1653. responsible for refreshing the rows after sorting, insertion and removal.
  1654. @class Backgrid.Body
  1655. @extends Backbone.View
  1656. */
  1657. var Body = Backgrid.Body = Backbone.View.extend({
  1658. /** @property */
  1659. tagName: "tbody",
  1660. /**
  1661. Initializer.
  1662. @param {Object} options
  1663. @param {Backbone.Collection} options.collection
  1664. @param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns
  1665. Column metadata.
  1666. @param {Backgrid.Row} [options.row=Backgrid.Row] The Row class to use.
  1667. @param {string} [options.emptyText] The text to display in the empty row.
  1668. @throws {TypeError} If options.columns or options.collection is undefined.
  1669. See Backgrid.Row.
  1670. */
  1671. initialize: function (options) {
  1672. Backgrid.requireOptions(options, ["columns", "collection"]);
  1673. this.columns = options.columns;
  1674. if (!(this.columns instanceof Backbone.Collection)) {
  1675. this.columns = new Columns(this.columns);
  1676. }
  1677. this.row = options.row || Row;
  1678. this.rows = this.collection.map(function (model) {
  1679. var row = new this.row({
  1680. columns: this.columns,
  1681. model: model
  1682. });
  1683. return row;
  1684. }, this);
  1685. this.emptyText = options.emptyText;
  1686. this._unshiftEmptyRowMayBe();
  1687. var collection = this.collection;
  1688. this.listenTo(collection, "add", this.insertRow);
  1689. this.listenTo(collection, "remove", this.removeRow);
  1690. this.listenTo(collection, "sort", this.refresh);
  1691. this.listenTo(collection, "reset", this.refresh);
  1692. this.listenTo(collection, "backgrid:edited", this.moveToNextCell);
  1693. },
  1694. _unshiftEmptyRowMayBe: function () {
  1695. if (this.rows.length === 0 && this.emptyText != null) {
  1696. this.rows.unshift(new EmptyRow({
  1697. emptyText: this.emptyText,
  1698. columns: this.columns
  1699. }));
  1700. }
  1701. },
  1702. /**
  1703. This method can be called either directly or as a callback to a
  1704. [Backbone.Collecton#add](http://backbonejs.org/#Collection-add) event.
  1705. When called directly, it accepts a model or an array of models and an
  1706. option hash just like
  1707. [Backbone.Collection#add](http://backbonejs.org/#Collection-add) and
  1708. delegates to it. Once the model is added, a new row is inserted into the
  1709. body and automatically rendered.
  1710. When called as a callback of an `add` event, splices a new row into the
  1711. body and renders it.
  1712. @param {Backbone.Model} model The model to render as a row.
  1713. @param {Backbone.Collection} collection When called directly, this
  1714. parameter is actually the options to
  1715. [Backbone.Collection#add](http://backbonejs.org/#Collection-add).
  1716. @param {Object} options When called directly, this must be null.
  1717. See:
  1718. - [Backbone.Collection#add](http://backbonejs.org/#Collection-add)
  1719. */
  1720. insertRow: function (model, collection, options) {
  1721. if (this.rows[0] instanceof EmptyRow) this.rows.pop().remove();
  1722. // insertRow() is called directly
  1723. if (!(collection instanceof Backbone.Collection) && !options) {
  1724. this.collection.add(model, (options = collection));
  1725. return;
  1726. }
  1727. options = _.extend({render: true}, options || {});
  1728. var row = new this.row({
  1729. columns: this.columns,
  1730. model: model
  1731. });
  1732. var index = collection.indexOf(model);
  1733. this.rows.splice(index, 0, row);
  1734. var $el = this.$el;
  1735. var $children = $el.children();
  1736. var $rowEl = row.render().$el;
  1737. if (options.render) {
  1738. if (index >= $children.length) {
  1739. $el.append($rowEl);
  1740. }
  1741. else {
  1742. $children.eq(index).before($rowEl);
  1743. }
  1744. }
  1745. },
  1746. /**
  1747. The method can be called either directly or as a callback to a
  1748. [Backbone.Collection#remove](http://backbonejs.org/#Collection-remove)
  1749. event.
  1750. When called directly, it accepts a model or an array of models and an
  1751. option hash just like
  1752. [Backbone.Collection#remove](http://backbonejs.org/#Collection-remove) and
  1753. delegates to it. Once the model is removed, a corresponding row is removed
  1754. from the body.
  1755. When called as a callback of a `remove` event, splices into the rows and
  1756. removes the row responsible for rendering the model.
  1757. @param {Backbone.Model} model The model to remove from the body.
  1758. @param {Backbone.Collection} collection When called directly, this
  1759. parameter is actually the options to
  1760. [Backbone.Collection#remove](http://backbonejs.org/#Collection-remove).
  1761. @param {Object} options When called directly, this must be null.
  1762. See:
  1763. - [Backbone.Collection#remove](http://backbonejs.org/#Collection-remove)
  1764. */
  1765. removeRow: function (model, collection, options) {
  1766. // removeRow() is called directly
  1767. if (!options) {
  1768. this.collection.remove(model, (options = collection));
  1769. this._unshiftEmptyRowMayBe();
  1770. return;
  1771. }
  1772. if (_.isUndefined(options.render) || options.render) {
  1773. this.rows[options.index].remove();
  1774. }
  1775. this.rows.splice(options.index, 1);
  1776. this._unshiftEmptyRowMayBe();
  1777. },
  1778. /**
  1779. Reinitialize all the rows inside the body and re-render them. Triggers a
  1780. Backbone `backgrid:refresh` event from the collection along with the body
  1781. instance as its sole parameter when done.
  1782. */
  1783. refresh: function () {
  1784. for (var i = 0; i < this.rows.length; i++) {
  1785. this.rows[i].remove();
  1786. }
  1787. this.rows = this.collection.map(function (model) {
  1788. var row = new this.row({
  1789. columns: this.columns,
  1790. model: model
  1791. });
  1792. return row;
  1793. }, this);
  1794. this._unshiftEmptyRowMayBe();
  1795. this.render();
  1796. this.collection.trigger("backgrid:refresh", this);
  1797. return this;
  1798. },
  1799. /**
  1800. Renders all the rows inside this body. If the collection is empty and
  1801. `options.emptyText` is defined and not null in the constructor, an empty
  1802. row is rendered, otherwise no row is rendered.
  1803. */
  1804. render: function () {
  1805. this.$el.empty();
  1806. var fragment = document.createDocumentFragment();
  1807. for (var i = 0; i < this.rows.length; i++) {
  1808. var row = this.rows[i];
  1809. fragment.appendChild(row.render().el);
  1810. }
  1811. this.el.appendChild(fragment);
  1812. this.delegateEvents();
  1813. return this;
  1814. },
  1815. /**
  1816. Clean up this body and it's rows.
  1817. @chainable
  1818. */
  1819. remove: function () {
  1820. for (var i = 0; i < this.rows.length; i++) {
  1821. var row = this.rows[i];
  1822. row.remove.apply(row, arguments);
  1823. }
  1824. return Backbone.View.prototype.remove.apply(this, arguments);
  1825. },
  1826. /**
  1827. Moves focus to the next renderable and editable cell and return the
  1828. currently editing cell to display mode.
  1829. @param {Backbone.Model} model The originating model
  1830. @param {Backgrid.Column} column The originating model column
  1831. @param {Backgrid.Command} command The Command object constructed from a DOM
  1832. Event
  1833. */
  1834. moveToNextCell: function (model, column, command) {
  1835. var i = this.collection.indexOf(model);
  1836. var j = this.columns.indexOf(column);
  1837. if (command.moveUp() || command.moveDown() || command.moveLeft() ||
  1838. command.moveRight() || command.save()) {
  1839. var l = this.columns.length;
  1840. var maxOffset = l * this.collection.length;
  1841. if (command.moveUp() || command.moveDown()) {
  1842. var row = this.rows[i + (command.moveUp() ? -1 : 1)];
  1843. if (row) row.cells[j].enterEditMode();
  1844. }
  1845. else if (command.moveLeft() || command.moveRight()) {
  1846. var right = command.moveRight();
  1847. for (var offset = i * l + j + (right ? 1 : -1);
  1848. offset >= 0 && offset < maxOffset;
  1849. right ? offset++ : offset--) {
  1850. var m = ~~(offset / l);
  1851. var n = offset - m * l;
  1852. var cell = this.rows[m].cells[n];
  1853. if (cell.column.get("renderable") && cell.column.get("editable")) {
  1854. cell.enterEditMode();
  1855. break;
  1856. }
  1857. }
  1858. }
  1859. }
  1860. this.rows[i].cells[j].exitEditMode();
  1861. }
  1862. });
  1863. /*
  1864. backgrid
  1865. http://github.com/wyuenho/backgrid
  1866. Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors
  1867. Licensed under the MIT @license.
  1868. */
  1869. /**
  1870. A Footer is a generic class that only defines a default tag `tfoot` and
  1871. number of required parameters in the initializer.
  1872. @abstract
  1873. @class Backgrid.Footer
  1874. @extends Backbone.View
  1875. */
  1876. var Footer = Backgrid.Footer = Backbone.View.extend({
  1877. /** @property */
  1878. tagName: "tfoot",
  1879. /**
  1880. Initializer.
  1881. @param {Object} options
  1882. @param {*} options.parent The parent view class of this footer.
  1883. @param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns
  1884. Column metadata.
  1885. @param {Backbone.Collection} options.collection
  1886. @throws {TypeError} If options.columns or options.collection is undefined.
  1887. */
  1888. initialize: function (options) {
  1889. Backgrid.requireOptions(options, ["columns", "collection"]);
  1890. this.columns = options.columns;
  1891. if (!(this.columns instanceof Backbone.Collection)) {
  1892. this.columns = new Backgrid.Columns(this.columns);
  1893. }
  1894. }
  1895. });
  1896. /*
  1897. backgrid
  1898. http://github.com/wyuenho/backgrid
  1899. Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors
  1900. Licensed under the MIT @license.
  1901. */
  1902. /**
  1903. Grid represents a data grid that has a header, body and an optional footer.
  1904. By default, a Grid treats each model in a collection as a row, and each
  1905. attribute in a model as a column. To render a grid you must provide a list of
  1906. column metadata and a collection to the Grid constructor. Just like any
  1907. Backbone.View class, the grid is rendered as a DOM node fragment when you
  1908. call render().
  1909. var grid = Backgrid.Grid({
  1910. columns: [{ name: "id", label: "ID", type: "string" },
  1911. // ...
  1912. ],
  1913. collections: books
  1914. });
  1915. $("#table-container").append(grid.render().el);
  1916. Optionally, if you want to customize the rendering of the grid's header and
  1917. footer, you may choose to extend Backgrid.Header and Backgrid.Footer, and
  1918. then supply that class or an instance of that class to the Grid constructor.
  1919. See the documentation for Header and Footer for further details.
  1920. var grid = Backgrid.Grid({
  1921. columns: [{ name: "id", label: "ID", type: "string" }],
  1922. collections: books,
  1923. header: Backgrid.Header.extend({
  1924. //...
  1925. }),
  1926. footer: Backgrid.Paginator
  1927. });
  1928. Finally, if you want to override how the rows are rendered in the table body,
  1929. you can supply a Body subclass as the `body` attribute that uses a different
  1930. Row class.
  1931. @class Backgrid.Grid
  1932. @extends Backbone.View
  1933. See:
  1934. - Backgrid.Column
  1935. - Backgrid.Header
  1936. - Backgrid.Body
  1937. - Backgrid.Row
  1938. - Backgrid.Footer
  1939. */
  1940. var Grid = Backgrid.Grid = Backbone.View.extend({
  1941. /** @property */
  1942. tagName: "table",
  1943. /** @property */
  1944. className: "backgrid",
  1945. /** @property */
  1946. header: Header,
  1947. /** @property */
  1948. body: Body,
  1949. /** @property */
  1950. footer: null,
  1951. /**
  1952. Initializes a Grid instance.
  1953. @param {Object} options
  1954. @param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata.
  1955. @param {Backbone.Collection} options.collection The collection of tabular model data to display.
  1956. @param {Backgrid.Header} [options.header=Backgrid.Header] An optional Header class to override the default.
  1957. @param {Backgrid.Body} [options.body=Backgrid.Body] An optional Body class to override the default.
  1958. @param {Backgrid.Row} [options.row=Backgrid.Row] An optional Row class to override the default.
  1959. @param {Backgrid.Footer} [options.footer=Backgrid.Footer] An optional Footer class.
  1960. */
  1961. initialize: function (options) {
  1962. Backgrid.requireOptions(options, ["columns", "collection"]);
  1963. // Convert the list of column objects here first so the subviews don't have
  1964. // to.
  1965. if (!(options.columns instanceof Backbone.Collection)) {
  1966. options.columns = new Columns(options.columns);
  1967. }
  1968. this.columns = options.columns;
  1969. var passedThruOptions = _.omit(options, ["el", "id", "attributes",
  1970. "className", "tagName", "events"]);
  1971. this.header = options.header || this.header;
  1972. this.header = new this.header(passedThruOptions);
  1973. this.body = options.body || this.body;
  1974. this.body = new this.body(passedThruOptions);
  1975. this.footer = options.footer || this.footer;
  1976. if (this.footer) {
  1977. this.footer = new this.footer(passedThruOptions);
  1978. }
  1979. this.listenTo(this.columns, "reset", function () {
  1980. this.header = new (this.header.remove().constructor)(passedThruOptions);
  1981. this.body = new (this.body.remove().constructor)(passedThruOptions);
  1982. if (this.footer) {
  1983. this.footer = new (this.footer.remove().constructor)(passedThruOptions);
  1984. }
  1985. this.render();
  1986. });
  1987. },
  1988. /**
  1989. Delegates to Backgrid.Body#insertRow.
  1990. */
  1991. insertRow: function (model, collection, options) {
  1992. return this.body.insertRow(model, collection, options);
  1993. },
  1994. /**
  1995. Delegates to Backgrid.Body#removeRow.
  1996. */
  1997. removeRow: function (model, collection, options) {
  1998. return this.body.removeRow(model, collection, options);
  1999. },
  2000. /**
  2001. Delegates to Backgrid.Columns#add for adding a column. Subviews can listen
  2002. to the `add` event from their internal `columns` if rerendering needs to
  2003. happen.
  2004. @param {Object} [options] Options for `Backgrid.Columns#add`.
  2005. @param {boolean} [options.render=true] Whether to render the column
  2006. immediately after insertion.
  2007. @chainable
  2008. */
  2009. insertColumn: function (column, options) {
  2010. options = options || {render: true};
  2011. this.columns.add(column, options);
  2012. return this;
  2013. },
  2014. /**
  2015. Delegates to Backgrid.Columns#remove for removing a column. Subviews can
  2016. listen to the `remove` event from the internal `columns` if rerendering
  2017. needs to happen.
  2018. @param {Object} [options] Options for `Backgrid.Columns#remove`.
  2019. @chainable
  2020. */
  2021. removeColumn: function (column, options) {
  2022. this.columns.remove(column, options);
  2023. return this;
  2024. },
  2025. /**
  2026. Renders the grid's header, then footer, then finally the body. Triggers a
  2027. Backbone `backgrid:rendered` event along with a reference to the grid when
  2028. the it has successfully been rendered.
  2029. */
  2030. render: function () {
  2031. this.$el.empty();
  2032. this.$el.append(this.header.render().$el);
  2033. if (this.footer) {
  2034. this.$el.append(this.footer.render().$el);
  2035. }
  2036. this.$el.append(this.body.render().$el);
  2037. this.delegateEvents();
  2038. this.trigger("backgrid:rendered", this);
  2039. return this;
  2040. },
  2041. /**
  2042. Clean up this grid and its subviews.
  2043. @chainable
  2044. */
  2045. remove: function () {
  2046. this.header.remove.apply(this.header, arguments);
  2047. this.body.remove.apply(this.body, arguments);
  2048. this.footer && this.footer.remove.apply(this.footer, arguments);
  2049. return Backbone.View.prototype.remove.apply(this, arguments);
  2050. }
  2051. });
  2052. }(this, jQuery, _, Backbone));