PageRenderTime 53ms CodeModel.GetById 17ms 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

Large files files are truncated, but you can click here to view the full file

  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",

Large files files are truncated, but you can click here to view the full file