PageRenderTime 71ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 1ms

/examples/js/backgrid.js

https://github.com/rickhewes/backbone-pageable
JavaScript | 2474 lines | 1091 code | 318 blank | 1065 comment | 233 complexity | e51e32470be1193c3ddb4ecabc3c112a 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.5",
  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 string formats.
  256. This class only understands ISO-8601 formatted datetime strings. See
  257. Backgrid.Extension.MomentFormatter if you need a much more flexible datetime
  258. formatter.
  259. @class Backgrid.DatetimeFormatter
  260. @extends Backgrid.CellFormatter
  261. @constructor
  262. @throws {Error} If both `includeDate` and `includeTime` are false.
  263. */
  264. var DatetimeFormatter = Backgrid.DatetimeFormatter = function (options) {
  265. options = options ? _.clone(options) : {};
  266. _.extend(this, this.defaults, options);
  267. if (!this.includeDate && !this.includeTime) {
  268. throw new Error("Either includeDate or includeTime must be true");
  269. }
  270. };
  271. DatetimeFormatter.prototype = new CellFormatter();
  272. _.extend(DatetimeFormatter.prototype, {
  273. /**
  274. @member Backgrid.DatetimeFormatter
  275. @cfg {Object} options
  276. @cfg {boolean} [options.includeDate=true] Whether the values include the
  277. date part.
  278. @cfg {boolean} [options.includeTime=true] Whether the values include the
  279. time part.
  280. @cfg {boolean} [options.includeMilli=false] If `includeTime` is true,
  281. whether to include the millisecond part, if it exists.
  282. */
  283. defaults: {
  284. includeDate: true,
  285. includeTime: true,
  286. includeMilli: false
  287. },
  288. DATE_RE: /^([+\-]?\d{4})-(\d{2})-(\d{2})$/,
  289. TIME_RE: /^(\d{2}):(\d{2}):(\d{2})(\.(\d{3}))?$/,
  290. ISO_SPLITTER_RE: /T|Z| +/,
  291. _convert: function (data, validate) {
  292. data = data.trim();
  293. var parts = data.split(this.ISO_SPLITTER_RE) || [];
  294. var date = this.DATE_RE.test(parts[0]) ? parts[0] : '';
  295. var time = date && parts[1] ? parts[1] : this.TIME_RE.test(parts[0]) ? parts[0] : '';
  296. var YYYYMMDD = this.DATE_RE.exec(date) || [];
  297. var HHmmssSSS = this.TIME_RE.exec(time) || [];
  298. if (validate) {
  299. if (this.includeDate && _.isUndefined(YYYYMMDD[0])) return;
  300. if (this.includeTime && _.isUndefined(HHmmssSSS[0])) return;
  301. if (!this.includeDate && date) return;
  302. if (!this.includeTime && time) return;
  303. }
  304. var jsDate = new Date(Date.UTC(YYYYMMDD[1] * 1 || 0,
  305. YYYYMMDD[2] * 1 - 1 || 0,
  306. YYYYMMDD[3] * 1 || 0,
  307. HHmmssSSS[1] * 1 || null,
  308. HHmmssSSS[2] * 1 || null,
  309. HHmmssSSS[3] * 1 || null,
  310. HHmmssSSS[5] * 1 || null));
  311. var result = '';
  312. if (this.includeDate) {
  313. result = lpad(jsDate.getUTCFullYear(), 4, 0) + '-' + lpad(jsDate.getUTCMonth() + 1, 2, 0) + '-' + lpad(jsDate.getUTCDate(), 2, 0);
  314. }
  315. if (this.includeTime) {
  316. result = result + (this.includeDate ? 'T' : '') + lpad(jsDate.getUTCHours(), 2, 0) + ':' + lpad(jsDate.getUTCMinutes(), 2, 0) + ':' + lpad(jsDate.getUTCSeconds(), 2, 0);
  317. if (this.includeMilli) {
  318. result = result + '.' + lpad(jsDate.getUTCMilliseconds(), 3, 0);
  319. }
  320. }
  321. if (this.includeDate && this.includeTime) {
  322. result += "Z";
  323. }
  324. return result;
  325. },
  326. /**
  327. Converts an ISO-8601 formatted datetime string to a datetime string, date
  328. string or a time string. The timezone is ignored if supplied.
  329. @member Backgrid.DatetimeFormatter
  330. @param {string} rawData
  331. @return {string|null|undefined} ISO-8601 string in UTC. Null and undefined
  332. values are returned as is.
  333. */
  334. fromRaw: function (rawData) {
  335. if (_.isNull(rawData) || _.isUndefined(rawData)) return '';
  336. return this._convert(rawData);
  337. },
  338. /**
  339. Converts an ISO-8601 formatted datetime string to a datetime string, date
  340. string or a time string. The timezone is ignored if supplied. This method
  341. parses the input values exactly the same way as
  342. Backgrid.Extension.MomentFormatter#fromRaw(), in addition to doing some
  343. sanity checks.
  344. @member Backgrid.DatetimeFormatter
  345. @param {string} formattedData
  346. @return {string|undefined} ISO-8601 string in UTC. Undefined if a date is
  347. found when `includeDate` is false, or a time is found when `includeTime` is
  348. false, or if `includeDate` is true and a date is not found, or if
  349. `includeTime` is true and a time is not found.
  350. */
  351. toRaw: function (formattedData) {
  352. return this._convert(formattedData, true);
  353. }
  354. });
  355. /**
  356. Formatter to convert any value to string.
  357. @class Backgrid.StringFormatter
  358. @extends Backgrid.CellFormatter
  359. @constructor
  360. */
  361. var StringFormatter = Backgrid.StringFormatter = function () {};
  362. StringFormatter.prototype = new CellFormatter();
  363. _.extend(StringFormatter.prototype, {
  364. /**
  365. Converts any value to a string using Ecmascript's implicit type
  366. conversion. If the given value is `null` or `undefined`, an empty string is
  367. returned instead.
  368. @member Backgrid.StringFormatter
  369. @param {*} rawValue
  370. @return {string}
  371. */
  372. fromRaw: function (rawValue) {
  373. if (_.isUndefined(rawValue) || _.isNull(rawValue)) return '';
  374. return rawValue + '';
  375. }
  376. });
  377. /**
  378. Simple email validation formatter.
  379. @class Backgrid.EmailFormatter
  380. @extends Backgrid.CellFormatter
  381. @constructor
  382. */
  383. var EmailFormatter = Backgrid.EmailFormatter = function () {};
  384. EmailFormatter.prototype = new CellFormatter();
  385. _.extend(EmailFormatter.prototype, {
  386. /**
  387. Return the input if it is a string that contains an '@' character and if
  388. the strings before and after '@' are non-empty. If the input does not
  389. validate, `undefined` is returned.
  390. @member Backgrid.EmailFormatter
  391. @param {*} formattedData
  392. @return {string|undefined}
  393. */
  394. toRaw: function (formattedData) {
  395. var parts = formattedData.trim().split("@");
  396. if (parts.length === 2 && _.all(parts)) {
  397. return formattedData;
  398. }
  399. }
  400. });
  401. /*
  402. backgrid
  403. http://github.com/wyuenho/backgrid
  404. Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors
  405. Licensed under the MIT @license.
  406. */
  407. /**
  408. Generic cell editor base class. Only defines an initializer for a number of
  409. required parameters.
  410. @abstract
  411. @class Backgrid.CellEditor
  412. @extends Backbone.View
  413. */
  414. var CellEditor = Backgrid.CellEditor = Backbone.View.extend({
  415. /**
  416. Initializer.
  417. @param {Object} options
  418. @param {Backgrid.CellFormatter} options.formatter
  419. @param {Backgrid.Column} options.column
  420. @param {Backbone.Model} options.model
  421. @throws {TypeError} If `formatter` is not a formatter instance, or when
  422. `model` or `column` are undefined.
  423. */
  424. initialize: function (options) {
  425. Backgrid.requireOptions(options, ["formatter", "column", "model"]);
  426. this.formatter = options.formatter;
  427. this.column = options.column;
  428. if (!(this.column instanceof Column)) {
  429. this.column = new Column(this.column);
  430. }
  431. this.listenTo(this.model, "backgrid:editing", this.postRender);
  432. },
  433. /**
  434. Post-rendering setup and initialization. Focuses the cell editor's `el` in
  435. this default implementation. **Should** be called by Cell classes after
  436. calling Backgrid.CellEditor#render.
  437. */
  438. postRender: function (model, column) {
  439. if (column == null || column.get("name") == this.column.get("name")) {
  440. this.$el.focus();
  441. }
  442. return this;
  443. }
  444. });
  445. /**
  446. InputCellEditor the cell editor type used by most core cell types. This cell
  447. editor renders a text input box as its editor. The input will render a
  448. placeholder if the value is empty on supported browsers.
  449. @class Backgrid.InputCellEditor
  450. @extends Backgrid.CellEditor
  451. */
  452. var InputCellEditor = Backgrid.InputCellEditor = CellEditor.extend({
  453. /** @property */
  454. tagName: "input",
  455. /** @property */
  456. attributes: {
  457. type: "text"
  458. },
  459. /** @property */
  460. events: {
  461. "blur": "saveOrCancel",
  462. "keydown": "saveOrCancel"
  463. },
  464. /**
  465. Initializer. Removes this `el` from the DOM when a `done` event is
  466. triggered.
  467. @param {Object} options
  468. @param {Backgrid.CellFormatter} options.formatter
  469. @param {Backgrid.Column} options.column
  470. @param {Backbone.Model} options.model
  471. @param {string} [options.placeholder]
  472. */
  473. initialize: function (options) {
  474. CellEditor.prototype.initialize.apply(this, arguments);
  475. if (options.placeholder) {
  476. this.$el.attr("placeholder", options.placeholder);
  477. }
  478. },
  479. /**
  480. Renders a text input with the cell value formatted for display, if it
  481. exists.
  482. */
  483. render: function () {
  484. this.$el.val(this.formatter.fromRaw(this.model.get(this.column.get("name"))));
  485. return this;
  486. },
  487. /**
  488. If the key pressed is `enter`, `tab`, `up`, or `down`, converts the value
  489. in the editor to a raw value for saving into the model using the formatter.
  490. If the key pressed is `esc` the changes are undone.
  491. If the editor goes out of focus (`blur`) but the value is invalid, the
  492. event is intercepted and cancelled so the cell remains in focus pending for
  493. further action. The changes are saved otherwise.
  494. Triggers a Backbone `backgrid:edited` event from the model when successful,
  495. and `backgrid:error` if the value cannot be converted. Classes listening to
  496. the `error` event, usually the Cell classes, should respond appropriately,
  497. usually by rendering some kind of error feedback.
  498. @param {Event} e
  499. */
  500. saveOrCancel: function (e) {
  501. var formatter = this.formatter;
  502. var model = this.model;
  503. var column = this.column;
  504. var command = new Command(e);
  505. var blurred = e.type === "blur";
  506. if (command.moveUp() || command.moveDown() || command.moveLeft() || command.moveRight() ||
  507. command.save() || blurred) {
  508. e.preventDefault();
  509. e.stopPropagation();
  510. var val = this.$el.val();
  511. var newValue = formatter.toRaw(val);
  512. if (_.isUndefined(newValue)) {
  513. model.trigger("backgrid:error", model, column, val);
  514. }
  515. else {
  516. model.set(column.get("name"), newValue);
  517. model.trigger("backgrid:edited", model, column, command);
  518. }
  519. }
  520. // esc
  521. else if (command.cancel()) {
  522. // undo
  523. e.stopPropagation();
  524. model.trigger("backgrid:edited", model, column, command);
  525. }
  526. },
  527. postRender: function (model, column) {
  528. if (column == null || column.get("name") == this.column.get("name")) {
  529. // move the cursor to the end on firefox if text is right aligned
  530. if (this.$el.css("text-align") === "right") {
  531. var val = this.$el.val();
  532. this.$el.focus().val(null).val(val);
  533. }
  534. else this.$el.focus();
  535. }
  536. return this;
  537. }
  538. });
  539. /**
  540. The super-class for all Cell types. By default, this class renders a plain
  541. table cell with the model value converted to a string using the
  542. formatter. The table cell is clickable, upon which the cell will go into
  543. editor mode, which is rendered by a Backgrid.InputCellEditor instance by
  544. default. Upon encountering any formatting errors, this class will add an
  545. `error` CSS class to the table cell.
  546. @abstract
  547. @class Backgrid.Cell
  548. @extends Backbone.View
  549. */
  550. var Cell = Backgrid.Cell = Backbone.View.extend({
  551. /** @property */
  552. tagName: "td",
  553. /**
  554. @property {Backgrid.CellFormatter|Object|string} [formatter=new CellFormatter()]
  555. */
  556. formatter: new CellFormatter(),
  557. /**
  558. @property {Backgrid.CellEditor} [editor=Backgrid.InputCellEditor] The
  559. default editor for all cell instances of this class. This value must be a
  560. class, it will be automatically instantiated upon entering edit mode.
  561. See Backgrid.CellEditor
  562. */
  563. editor: InputCellEditor,
  564. /** @property */
  565. events: {
  566. "click": "enterEditMode"
  567. },
  568. /**
  569. Initializer.
  570. @param {Object} options
  571. @param {Backbone.Model} options.model
  572. @param {Backgrid.Column} options.column
  573. @throws {ReferenceError} If formatter is a string but a formatter class of
  574. said name cannot be found in the Backgrid module.
  575. */
  576. initialize: function (options) {
  577. Backgrid.requireOptions(options, ["model", "column"]);
  578. this.column = options.column;
  579. if (!(this.column instanceof Column)) {
  580. this.column = new Column(this.column);
  581. }
  582. this.formatter = Backgrid.resolveNameToClass(this.column.get("formatter") || this.formatter, "Formatter");
  583. this.editor = Backgrid.resolveNameToClass(this.editor, "CellEditor");
  584. this.listenTo(this.model, "change:" + this.column.get("name"), function () {
  585. if (!this.$el.hasClass("editor")) this.render();
  586. });
  587. },
  588. /**
  589. Render a text string in a table cell. The text is converted from the
  590. model's raw value for this cell's column.
  591. */
  592. render: function () {
  593. this.$el.empty();
  594. this.$el.text(this.formatter.fromRaw(this.model.get(this.column.get("name"))));
  595. this.delegateEvents();
  596. return this;
  597. },
  598. /**
  599. If this column is editable, a new CellEditor instance is instantiated with
  600. its required parameters. An `editor` CSS class is added to the cell upon
  601. entering edit mode.
  602. This method triggers a Backbone `backgrid:edit` event from the model when
  603. the cell is entering edit mode and an editor instance has been constructed,
  604. but before it is rendered and inserted into the DOM. The cell and the
  605. constructed cell editor instance are sent as event parameters when this
  606. event is triggered.
  607. When this cell has finished switching to edit mode, a Backbone
  608. `backgrid:editing` event is triggered from the model. The cell and the
  609. constructed cell instance are also sent as parameters in the event.
  610. When the model triggers a `backgrid:error` event, it means the editor is
  611. unable to convert the current user input to an apprpriate value for the
  612. model's column, and an `error` CSS class is added to the cell accordingly.
  613. */
  614. enterEditMode: function () {
  615. var model = this.model;
  616. var column = this.column;
  617. if (column.get("editable")) {
  618. this.currentEditor = new this.editor({
  619. column: this.column,
  620. model: this.model,
  621. formatter: this.formatter
  622. });
  623. model.trigger("backgrid:edit", model, column, this, this.currentEditor);
  624. this.listenTo(model, "backgrid:error", this.renderError);
  625. // Need to redundantly undelegate events for Firefox
  626. this.undelegateEvents();
  627. this.$el.empty();
  628. this.$el.append(this.currentEditor.$el);
  629. this.currentEditor.render();
  630. this.$el.addClass("editor");
  631. model.trigger("backgrid:editing", model, column, this, this.currentEditor);
  632. }
  633. },
  634. /**
  635. Put an `error` CSS class on the table cell.
  636. */
  637. renderError: function (model, column) {
  638. if (column == null || column.get("name") == this.column.get("name")) {
  639. this.$el.addClass("error");
  640. }
  641. },
  642. /**
  643. Removes the editor and re-render in display mode.
  644. */
  645. exitEditMode: function () {
  646. this.$el.removeClass("error");
  647. this.currentEditor.remove();
  648. this.stopListening(this.currentEditor);
  649. delete this.currentEditor;
  650. this.$el.removeClass("editor");
  651. this.render();
  652. },
  653. /**
  654. Clean up this cell.
  655. @chainable
  656. */
  657. remove: function () {
  658. if (this.currentEditor) {
  659. this.currentEditor.remove.apply(this, arguments);
  660. delete this.currentEditor;
  661. }
  662. return Backbone.View.prototype.remove.apply(this, arguments);
  663. }
  664. });
  665. /**
  666. StringCell displays HTML escaped strings and accepts anything typed in.
  667. @class Backgrid.StringCell
  668. @extends Backgrid.Cell
  669. */
  670. var StringCell = Backgrid.StringCell = Cell.extend({
  671. /** @property */
  672. className: "string-cell",
  673. formatter: new StringFormatter()
  674. });
  675. /**
  676. UriCell renders an HTML `<a>` anchor for the value and accepts URIs as user
  677. input values. No type conversion or URL validation is done by the formatter
  678. of this cell. Users who need URL validation are encourage to subclass UriCell
  679. to take advantage of the parsing capabilities of the HTMLAnchorElement
  680. available on HTML5-capable browsers or using a third-party library like
  681. [URI.js](https://github.com/medialize/URI.js).
  682. @class Backgrid.UriCell
  683. @extends Backgrid.Cell
  684. */
  685. var UriCell = Backgrid.UriCell = Cell.extend({
  686. /** @property */
  687. className: "uri-cell",
  688. render: function () {
  689. this.$el.empty();
  690. var formattedValue = this.formatter.fromRaw(this.model.get(this.column.get("name")));
  691. this.$el.append($("<a>", {
  692. tabIndex: -1,
  693. href: formattedValue,
  694. title: formattedValue,
  695. target: "_blank"
  696. }).text(formattedValue));
  697. this.delegateEvents();
  698. return this;
  699. }
  700. });
  701. /**
  702. Like Backgrid.UriCell, EmailCell renders an HTML `<a>` anchor for the
  703. value. The `href` in the anchor is prefixed with `mailto:`. EmailCell will
  704. complain if the user enters a string that doesn't contain the `@` sign.
  705. @class Backgrid.EmailCell
  706. @extends Backgrid.StringCell
  707. */
  708. var EmailCell = Backgrid.EmailCell = StringCell.extend({
  709. /** @property */
  710. className: "email-cell",
  711. formatter: new EmailFormatter(),
  712. render: function () {
  713. this.$el.empty();
  714. var formattedValue = this.formatter.fromRaw(this.model.get(this.column.get("name")));
  715. this.$el.append($("<a>", {
  716. tabIndex: -1,
  717. href: "mailto:" + formattedValue,
  718. title: formattedValue
  719. }).text(formattedValue));
  720. this.delegateEvents();
  721. return this;
  722. }
  723. });
  724. /**
  725. NumberCell is a generic cell that renders all numbers. Numbers are formatted
  726. using a Backgrid.NumberFormatter.
  727. @class Backgrid.NumberCell
  728. @extends Backgrid.Cell
  729. */
  730. var NumberCell = Backgrid.NumberCell = Cell.extend({
  731. /** @property */
  732. className: "number-cell",
  733. /**
  734. @property {number} [decimals=2] Must be an integer.
  735. */
  736. decimals: NumberFormatter.prototype.defaults.decimals,
  737. /** @property {string} [decimalSeparator='.'] */
  738. decimalSeparator: NumberFormatter.prototype.defaults.decimalSeparator,
  739. /** @property {string} [orderSeparator=','] */
  740. orderSeparator: NumberFormatter.prototype.defaults.orderSeparator,
  741. /** @property {Backgrid.CellFormatter} [formatter=Backgrid.NumberFormatter] */
  742. formatter: NumberFormatter,
  743. /**
  744. Initializes this cell and the number formatter.
  745. @param {Object} options
  746. @param {Backbone.Model} options.model
  747. @param {Backgrid.Column} options.column
  748. */
  749. initialize: function (options) {
  750. Cell.prototype.initialize.apply(this, arguments);
  751. this.formatter = new this.formatter({
  752. decimals: this.decimals,
  753. decimalSeparator: this.decimalSeparator,
  754. orderSeparator: this.orderSeparator
  755. });
  756. }
  757. });
  758. /**
  759. An IntegerCell is just a Backgrid.NumberCell with 0 decimals. If a floating
  760. point number is supplied, the number is simply rounded the usual way when
  761. displayed.
  762. @class Backgrid.IntegerCell
  763. @extends Backgrid.NumberCell
  764. */
  765. var IntegerCell = Backgrid.IntegerCell = NumberCell.extend({
  766. /** @property */
  767. className: "integer-cell",
  768. /**
  769. @property {number} decimals Must be an integer.
  770. */
  771. decimals: 0
  772. });
  773. /**
  774. DatetimeCell is a basic cell that accepts datetime string values in RFC-2822
  775. or W3C's subset of ISO-8601 and displays them in ISO-8601 format. For a much
  776. more sophisticated date time cell with better datetime formatting, take a
  777. look at the Backgrid.Extension.MomentCell extension.
  778. @class Backgrid.DatetimeCell
  779. @extends Backgrid.Cell
  780. See:
  781. - Backgrid.Extension.MomentCell
  782. - Backgrid.DatetimeFormatter
  783. */
  784. var DatetimeCell = Backgrid.DatetimeCell = Cell.extend({
  785. /** @property */
  786. className: "datetime-cell",
  787. /**
  788. @property {boolean} [includeDate=true]
  789. */
  790. includeDate: DatetimeFormatter.prototype.defaults.includeDate,
  791. /**
  792. @property {boolean} [includeTime=true]
  793. */
  794. includeTime: DatetimeFormatter.prototype.defaults.includeTime,
  795. /**
  796. @property {boolean} [includeMilli=false]
  797. */
  798. includeMilli: DatetimeFormatter.prototype.defaults.includeMilli,
  799. /** @property {Backgrid.CellFormatter} [formatter=Backgrid.DatetimeFormatter] */
  800. formatter: DatetimeFormatter,
  801. /**
  802. Initializes this cell and the datetime formatter.
  803. @param {Object} options
  804. @param {Backbone.Model} options.model
  805. @param {Backgrid.Column} options.column
  806. */
  807. initialize: function (options) {
  808. Cell.prototype.initialize.apply(this, arguments);
  809. this.formatter = new this.formatter({
  810. includeDate: this.includeDate,
  811. includeTime: this.includeTime,
  812. includeMilli: this.includeMilli
  813. });
  814. var placeholder = this.includeDate ? "YYYY-MM-DD" : "";
  815. placeholder += (this.includeDate && this.includeTime) ? "T" : "";
  816. placeholder += this.includeTime ? "HH:mm:ss" : "";
  817. placeholder += (this.includeTime && this.includeMilli) ? ".SSS" : "";
  818. this.editor = this.editor.extend({
  819. attributes: _.extend({}, this.editor.prototype.attributes, this.editor.attributes, {
  820. placeholder: placeholder
  821. })
  822. });
  823. }
  824. });
  825. /**
  826. DateCell is a Backgrid.DatetimeCell without the time part.
  827. @class Backgrid.DateCell
  828. @extends Backgrid.DatetimeCell
  829. */
  830. var DateCell = Backgrid.DateCell = DatetimeCell.extend({
  831. /** @property */
  832. className: "date-cell",
  833. /** @property */
  834. includeTime: false
  835. });
  836. /**
  837. TimeCell is a Backgrid.DatetimeCell without the date part.
  838. @class Backgrid.TimeCell
  839. @extends Backgrid.DatetimeCell
  840. */
  841. var TimeCell = Backgrid.TimeCell = DatetimeCell.extend({
  842. /** @property */
  843. className: "time-cell",
  844. /** @property */
  845. includeDate: false
  846. });
  847. /**
  848. BooleanCellEditor renders a checkbox as its editor.
  849. @class Backgrid.BooleanCellEditor
  850. @extends Backgrid.CellEditor
  851. */
  852. var BooleanCellEditor = Backgrid.BooleanCellEditor = CellEditor.extend({
  853. /** @property */
  854. tagName: "input",
  855. /** @property */
  856. attributes: {
  857. tabIndex: -1,
  858. type: "checkbox"
  859. },
  860. /** @property */
  861. events: {
  862. "mousedown": function () {
  863. this.mouseDown = true;
  864. },
  865. "blur": "enterOrExitEditMode",
  866. "mouseup": function () {
  867. this.mouseDown = false;
  868. },
  869. "change": "saveOrCancel",
  870. "keydown": "saveOrCancel"
  871. },
  872. /**
  873. Renders a checkbox and check it if the model value of this column is true,
  874. uncheck otherwise.
  875. */
  876. render: function () {
  877. var val = this.formatter.fromRaw(this.model.get(this.column.get("name")));
  878. this.$el.prop("checked", val);
  879. return this;
  880. },
  881. /**
  882. Event handler. Hack to deal with the case where `blur` is fired before
  883. `change` and `click` on a checkbox.
  884. */
  885. enterOrExitEditMode: function (e) {
  886. if (!this.mouseDown) {
  887. var model = this.model;
  888. model.trigger("backgrid:edited", model, this.column, new Command(e));
  889. }
  890. },
  891. /**
  892. Event handler. Save the value into the model if the event is `change` or
  893. one of the keyboard navigation key presses. Exit edit mode without saving
  894. if `escape` was pressed.
  895. */
  896. saveOrCancel: function (e) {
  897. var model = this.model;
  898. var column = this.column;
  899. var formatter = this.formatter;
  900. var command = new Command(e);
  901. // skip ahead to `change` when space is pressed
  902. if (command.passThru() && e.type != "change") return true;
  903. if (command.cancel()) {
  904. e.stopPropagation();
  905. model.trigger("backgrid:edited", model, column, command);
  906. }
  907. var $el = this.$el;
  908. if (command.save() || command.moveLeft() || command.moveRight() || command.moveUp() ||
  909. command.moveDown()) {
  910. e.preventDefault();
  911. e.stopPropagation();
  912. var val = formatter.toRaw($el.prop("checked"));
  913. model.set(column.get("name"), val);
  914. model.trigger("backgrid:edited", model, column, command);
  915. }
  916. else if (e.type == "change") {
  917. var val = formatter.toRaw($el.prop("checked"));
  918. model.set(column.get("name"), val);
  919. $el.focus();
  920. }
  921. }
  922. });
  923. /**
  924. BooleanCell renders a checkbox both during display mode and edit mode. The
  925. checkbox is checked if the model value is true, unchecked otherwise.
  926. @class Backgrid.BooleanCell
  927. @extends Backgrid.Cell
  928. */
  929. var BooleanCell = Backgrid.BooleanCell = Cell.extend({
  930. /** @property */
  931. className: "boolean-cell",
  932. /** @property */
  933. editor: BooleanCellEditor,
  934. /** @property */
  935. events: {
  936. "click": "enterEditMode"
  937. },
  938. /**
  939. Renders a checkbox and check it if the model value of this column is true,
  940. uncheck otherwise.
  941. */
  942. render: function () {
  943. this.$el.empty();
  944. this.$el.append($("<input>", {
  945. tabIndex: -1,
  946. type: "checkbox",
  947. checked: this.formatter.fromRaw(this.model.get(this.column.get("name")))
  948. }));
  949. this.delegateEvents();
  950. return this;
  951. }
  952. });
  953. /**
  954. SelectCellEditor renders an HTML `<select>` fragment as the editor.
  955. @class Backgrid.SelectCellEditor
  956. @extends Backgrid.CellEditor
  957. */
  958. var SelectCellEditor = Backgrid.SelectCellEditor = CellEditor.extend({
  959. /** @property */
  960. tagName: "select",
  961. /** @property */
  962. events: {
  963. "change": "save",
  964. "blur": "close",
  965. "keydown": "close"
  966. },
  967. /** @property {function(Object, ?Object=): string} template */
  968. template: _.template('<option value="<%- value %>" <%= selected ? \'selected="selected"\' : "" %>><%- text %></option>'),
  969. setOptionValues: function (optionValues) {
  970. this.optionValues = optionValues;
  971. },
  972. _renderOptions: function (nvps, currentValue) {
  973. var options = '';
  974. for (var i = 0; i < nvps.length; i++) {
  975. options = options + this.template({
  976. text: nvps[i][0],
  977. value: nvps[i][1],
  978. selected: currentValue == nvps[i][1]
  979. });
  980. }
  981. return options;
  982. },
  983. /**
  984. Renders the options if `optionValues` is a list of name-value pairs. The
  985. options are contained inside option groups if `optionValues` is a list of
  986. object hashes. The name is rendered at the option text and the value is the
  987. option value. If `optionValues` is a function, it is called without a
  988. parameter.
  989. */
  990. render: function () {
  991. this.$el.empty();
  992. var optionValues = _.result(this, "optionValues");
  993. var currentValue = this.model.get(this.column.get("name"));
  994. if (!_.isArray(optionValues)) throw TypeError("optionValues must be an array");
  995. var optionValue = null;
  996. var optionText = null;
  997. var optionValue = null;
  998. var optgroupName = null;
  999. var optgroup = null;
  1000. for (var i = 0; i < optionValues.length; i++) {
  1001. var optionValue = optionValues[i];
  1002. if (_.isArray(optionValue)) {
  1003. optionText = optionValue[0];
  1004. optionValue = optionValue[1];
  1005. this.$el.append(this.template({
  1006. text: optionText,
  1007. value: optionValue,
  1008. selected: optionValue == currentValue
  1009. }));
  1010. }
  1011. else if (_.isObject(optionValue)) {
  1012. optgroupName = optionValue.name;
  1013. optgroup = $("<optgroup></optgroup>", { label: optgroupName });
  1014. optgroup.append(this._renderOptions(optionValue.values, currentValue));
  1015. this.$el.append(optgroup);
  1016. }
  1017. else {
  1018. throw TypeError("optionValues elements must be a name-value pair or an object hash of { name: 'optgroup label', value: [option name-value pairs] }");
  1019. }
  1020. }
  1021. this.delegateEvents();
  1022. return this;
  1023. },
  1024. /**
  1025. Saves the value of the selected option to the model attribute. Triggers a
  1026. `backgrid:edited` Backbone event from the model.
  1027. */
  1028. save: function (e) {
  1029. var model = this.model;
  1030. var column = this.column;
  1031. model.set(column.get("name"), this.formatter.toRaw(this.$el.val()));
  1032. model.trigger("backgrid:edited", model, column, new Command(e));
  1033. },
  1034. /**
  1035. Triggers a `backgrid:edited` event from the model so the body can close
  1036. this editor.
  1037. */
  1038. close: function (e) {
  1039. var model = this.model;
  1040. var column = this.column;
  1041. var command = new Command(e);
  1042. if (command.cancel()) {
  1043. e.stopPropagation();
  1044. model.trigger("backgrid:edited", model, column, new Command(e));
  1045. }
  1046. else if (command.save() || command.moveLeft() || command.moveRight() ||
  1047. command.moveUp() || command.moveDown() || e.type == "blur") {
  1048. e.preventDefault();
  1049. e.stopPropagation();
  1050. model.trigger("backgrid:edited", model, column, new Command(e));
  1051. }
  1052. }
  1053. });
  1054. /**
  1055. SelectCell is also a different kind of cell in that upon going into edit mode
  1056. the cell renders a list of options for to pick from, as opposed to an input
  1057. box.
  1058. SelectCell cannot be referenced by its string name when used in a column
  1059. definition because requires an `optionValues` class attribute to be
  1060. defined. `optionValues` can either be a list of name-value pairs, to be
  1061. rendered as options, or a list of object hashes which consist of a key *name*
  1062. which is the option group name, and a key *values* which is a list of
  1063. name-value pairs to be rendered as options under that option group.
  1064. In addition, `optionValues` can also be a parameter-less function that
  1065. returns one of the above. If the options are static, it is recommended the
  1066. returned values to be memoized. _.memoize() is a good function to help with
  1067. that.
  1068. Lastly, since this class uses the default CellFormatter, during display mode,
  1069. the raw model value is compared with the `optionValues` values using
  1070. Ecmascript's implicit type conversion rules. When exiting edit mode, no type
  1071. conversion is performed when saving into the model. This behavior is not
  1072. always desirable when the value type is anything other than string. To
  1073. control type conversion on the client-side, you should subclass SelectCell to
  1074. provide a custom formatter or provide the formatter to your column
  1075. definition.
  1076. @class Backgrid.SelectCell
  1077. @extends Backgrid.Cell
  1078. */
  1079. var SelectCell = Backgrid.SelectCell = Cell.extend({
  1080. /** @property */
  1081. className: "select-cell",
  1082. /** @property */
  1083. editor: SelectCellEditor,
  1084. /**
  1085. @property {Array.<Array>|Array.<{name: string, values: Array.<Array>}>} optionValues
  1086. */
  1087. optionValues: undefined,
  1088. /**
  1089. Initializer.
  1090. @param {Object} options
  1091. @param {Backbone.Model} options.model
  1092. @param {Backgrid.Column} options.column
  1093. @throws {TypeError} If `optionsValues` is undefined.
  1094. */
  1095. initialize: function (options) {
  1096. Cell.prototype.initialize.apply(this, arguments);
  1097. Backgrid.requireOptions(this, ["optionValues"]);
  1098. this.optionValues = _.result(this, "optionValues");
  1099. this.listenTo(this.model, "backgrid:edit", function (model, column, cell, editor) {
  1100. if (column.get("name") == this.column.get("name")) {
  1101. editor.setOptionValues(this.optionValues);
  1102. }
  1103. });
  1104. },
  1105. /**
  1106. Renders the label using the raw value as key to look up from `optionValues`.
  1107. @throws {TypeError} If `optionValues` is malformed.
  1108. */
  1109. render: function () {
  1110. this.$el.empty();
  1111. var optionValues = this.optionValues;
  1112. var rawData = this.formatter.fromRaw(this.model.get(this.column.get("name")));
  1113. try {
  1114. if (!_.isArray(optionValues) || _.isEmpty(optionValues)) throw new TypeError;
  1115. for (var i = 0; i < optionValues.length; i++) {
  1116. var optionValue = optionValues[i];
  1117. if (_.isArray(optionValue)) {
  1118. var optionText = optionValue[0];
  1119. var optionValue = optionValue[1];
  1120. if (optionValue == rawData) {
  1121. this.$el.append(optionText);
  1122. break;
  1123. }
  1124. }
  1125. else if (_.isObject(optionValue)) {
  1126. var optionGroupValues = optionValue.values;
  1127. for (var j = 0; j < optionGroupValues.length; j++) {
  1128. var optionGroupValue = optionGroupValues[j];
  1129. if (optionGroupValue[1] == rawData) {
  1130. this.$el.append(optionGroupValue[0]);
  1131. break;
  1132. }
  1133. }
  1134. }
  1135. else {
  1136. throw new TypeError;
  1137. }
  1138. }
  1139. }
  1140. catch (ex) {
  1141. if (ex instanceof TypeError) {
  1142. throw TypeError("'optionValues' must be of type {Array.<Array>|Array.<{name: string, values: Array.<Array>}>}");
  1143. }
  1144. throw ex;
  1145. }
  1146. this.delegateEvents();
  1147. return this;
  1148. }
  1149. });
  1150. /*
  1151. backgrid
  1152. http://github.com/wyuenho/backgrid
  1153. Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors
  1154. Licensed under the MIT @license.
  1155. */
  1156. /**
  1157. A Column is a placeholder for column metadata.
  1158. You usually don't need to create an instance of this class yourself as a
  1159. collection of column instances will be created for you from a list of column
  1160. attributes in the Backgrid.js view class constructors.
  1161. @class Backgrid.Column
  1162. @extends Backbone.Model
  1163. */
  1164. var Column = Backgrid.Column = Backbone.Model.extend({
  1165. defaults: {
  1166. name: undefined,
  1167. label: undefined,
  1168. sortable: true,
  1169. editable: true,
  1170. renderable: true,
  1171. formatter: undefined,
  1172. cell: undefined,
  1173. headerCell: undefined
  1174. },
  1175. /**
  1176. Initializes this Column instance.
  1177. @param {Object} attrs Column attributes.
  1178. @param {string} attrs.name The name of the model attribute.
  1179. @param {string|Backgrid.Cell} attrs.cell The cell type.
  1180. If this is a string, the capitalized form will be used to look up a
  1181. cell class in Backbone, i.e.: string => StringCell. If a Cell subclass
  1182. is supplied, it is initialized with a hash of parameters. If a Cell
  1183. instance is supplied, it is used directly.
  1184. @param {string|Backgrid.HeaderCell} [attrs.headerCell] The header cell type.
  1185. @param {string} [attrs.label] The label to show in the header.
  1186. @param {boolean} [attrs.sortable=true]
  1187. @param {boolean} [attrs.editable=true]
  1188. @param {boolean} [attrs.renderable=true]
  1189. @param {Backgrid.CellFormatter|Object|string} [attrs.formatter] The
  1190. formatter to use to convert between raw model values and user input.
  1191. @throws {TypeError} If attrs.cell or attrs.options are not supplied.
  1192. @throws {ReferenceError} If attrs.cell is a string but a cell class of
  1193. said name cannot be found in the Backgrid module.
  1194. See:
  1195. - Backgrid.Cell
  1196. - Backgrid.CellFormatter
  1197. */
  1198. initialize: function (attrs) {
  1199. Backgrid.requireOptions(attrs, ["cell", "name"]);
  1200. if (!this.has("label")) {
  1201. this.set({ label: this.get("name") }, { silent: true });
  1202. }
  1203. var headerCell = Backgrid.resolveNameToClass(this.get("headerCell"), "HeaderCell");
  1204. var cell = Backgrid.resolveNameToClass(this.get("cell"), "Cell");
  1205. this.set({ cell: cell, headerCell: headerCell }, { silent: true });
  1206. }
  1207. });
  1208. /**
  1209. A Backbone collection of Column instances.
  1210. @class Backgrid.Columns
  1211. @extends Backbone.Collection
  1212. */
  1213. var Columns = Backgrid.Columns = Backbone.Collection.extend({
  1214. /**
  1215. @property {Backgrid.Column} model
  1216. */
  1217. model: Column
  1218. });
  1219. /*
  1220. backgrid
  1221. http://github.com/wyuenho/backgrid
  1222. Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors
  1223. Licensed under the MIT @license.
  1224. */
  1225. /**
  1226. Row is a simple container view that takes a model instance and a list of
  1227. column metadata describing how each of the model's attribute is to be
  1228. rendered, and apply the appropriate cell to each attribute.
  1229. @class Backgrid.Row
  1230. @extends Backbone.View
  1231. */
  1232. var Row = Backgrid.Row = Backbone.View.extend({
  1233. /** @property */
  1234. tagName: "tr",
  1235. requiredOptions: ["columns", "model"],
  1236. /**
  1237. Initializes a row view instance.
  1238. @param {Object} options
  1239. @param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata.
  1240. @param {Backbone.Model} options.model The model instance to render.
  1241. @throws {TypeError} If options.columns or options.model is undefined.
  1242. */
  1243. initialize: function (options) {
  1244. Backgrid.requireOptions(options, this.requiredOptions);
  1245. var columns = this.columns = options.columns;
  1246. if (!(columns instanceof Backbone.Collection)) {
  1247. columns = this.columns = new Columns(columns);
  1248. }
  1249. var cells = this.cells = [];
  1250. for (var i = 0; i < columns.length; i++) {
  1251. cells.push(this.makeCell(columns.at(i), options));
  1252. }
  1253. this.listenTo(columns, "change:renderable", function (column, renderable) {
  1254. for (var i = 0; i < cells.length; i++) {
  1255. var cell = cells[i];
  1256. if (cell.column.get("name") == column.get("name")) {
  1257. if (renderable) cell.$el.show(); else cell.$el.hide();
  1258. }
  1259. }
  1260. });
  1261. this.listenTo(columns, "add", function (column, columns) {
  1262. var i = columns.indexOf(column);
  1263. var cell = this.makeCell(column, options);
  1264. cells.splice(i, 0, cell);
  1265. if (!cell.column.get("renderable")) cell.$el.hide();
  1266. var $el = this.$el;
  1267. if (i === 0) {
  1268. $el.prepend(cell.render().$el);
  1269. }
  1270. else if (i === columns.length - 1) {
  1271. $el.append(cell.render().$el);
  1272. }
  1273. else {
  1274. $el.children().eq(i).before(cell.render().$el);
  1275. }
  1276. });
  1277. this.listenTo(columns, "remove", function (column, columns, opts) {
  1278. cells[opts.index].remove();
  1279. cells.splice(opts.index, 1);
  1280. });
  1281. },
  1282. /**
  1283. Factory method for making a cell. Used by #initialize internally. Override
  1284. this to provide an appropriate cell instance for a custom Row subclass.
  1285. @protected
  1286. @param {Backgrid.Column} column
  1287. @param {Object} options The options passed to #initialize.
  1288. @return {Backgrid.Cell}
  1289. */
  1290. makeCell: function (column) {
  1291. return new (column.get("cell"))({
  1292. column: column,
  1293. model: this.model
  1294. });
  1295. },
  1296. /**
  1297. Renders a row of cells for this row's model.
  1298. */
  1299. render: function () {
  1300. this.$el.empty();
  1301. var fragment = document.createDocumentFragment();
  1302. for (var i = 0; i < this.cells.length; i++) {
  1303. var cell = this.cells[i];
  1304. fragment.appendChild(cell.render().el);
  1305. if (!cell.column.get("renderable")) cell.$el.hide();
  1306. }
  1307. this.el.appendChild(fragment);
  1308. this.delegateEvents();
  1309. return this;
  1310. },
  1311. /**
  1312. Clean up this row and its cells.
  1313. @chainable
  1314. */
  1315. remove: function () {
  1316. for (var i = 0; i < this.cells.length; i++) {
  1317. var cell = this.cells[i];
  1318. cell.remove.apply(cell, arguments);
  1319. }
  1320. return Backbone.View.prototype.remove.apply(this, arguments);
  1321. }
  1322. });
  1323. /**
  1324. EmptyRow is a simple container view that takes a list of column and render a
  1325. row with a single column.
  1326. @class Backgrid.EmptyRow
  1327. @extends Backbone.View
  1328. */
  1329. var EmptyRow = Backgrid.EmptyRow = Backbone.View.extend({
  1330. /** @property */
  1331. tagName: "tr",
  1332. /** @property */
  1333. emptyText: null,
  1334. /**
  1335. Initializer.
  1336. @param {Object} options
  1337. @param {string} options.emptyText
  1338. @param {Backbone.Collection.<Backgrid.Column>|Array.<Backgrid.Column>|Array.<Object>} options.columns Column metadata.
  1339. */
  1340. initialize: function (options) {
  1341. Backgrid.requireOptions(options, ["emptyText", "columns"]);
  1342. this.emptyText = options.emptyText;
  1343. this.columns = options.columns;
  1344. },
  1345. /**
  1346. Renders an empty row.
  1347. */
  1348. render: function () {
  1349. this.$el.empty();
  1350. var td = document.createElement("td");
  1351. td.setAttribute("colspan", this.columns.length);
  1352. td.textContent = this.emptyText;
  1353. this.el.setAttribute("class", "empty");
  1354. this.el.appendChild(td);
  1355. return this;
  1356. }
  1357. });
  1358. /*
  1359. backgrid
  1360. http://github.com/wyuenho/backgrid
  1361. Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors
  1362. Licensed under the MIT @license.
  1363. */
  1364. /**
  1365. HeaderCell is a special cell class that renders a column header cell. If the
  1366. column is sortable, a sorter is also rendered and will trigger a table
  1367. refresh after sorting.
  1368. @class Backgrid.HeaderCell
  1369. @extends Backbone.View
  1370. */
  1371. var HeaderCell = Backgrid.HeaderCell = Backbone.View.extend({
  1372. /** @property */
  1373. tagName: "th",
  1374. /** @property */
  1375. events: {
  1376. "click a": "onClick"
  1377. },
  1378. /**
  1379. @property {null|"ascending"|"descending"} _direction The current sorting
  1380. direction of this column.
  1381. */
  1382. _direction: null,
  1383. /**
  1384. Initializer.
  1385. @param {Object} options
  1386. @param {Backgrid.Column|Object} options.column
  1387. @throws {TypeError} If options.column or options.collection is undefined.
  1388. */
  1389. initialize: function (options) {
  1390. Backgrid.requireOptions(options, ["column", "collection"]);
  1391. this.column = options.column;
  1392. if (!(this.column instanceof Column)) {
  1393. this.column = new Column(this.column);
  1394. }
  1395. this.listenTo(this.collection, "backgrid:sort", this._resetCellDirection);
  1396. },
  1397. /**
  1398. Gets or sets the direction of this cell. If called directly without
  1399. parameters, returns the current direction of this cell, otherwise sets
  1400. it. If a `null` is given, sets this cell back to the default order.
  1401. @param {null|"ascending"|"descending"} dir
  1402. @return {null|string} The current direction or the changed direction.
  1403. */
  1404. direction: function (dir) {
  1405. if (arguments.length) {
  1406. if (this._direction) this.$el.removeClass(this._direction);
  1407. if (dir) this.$el.addClass(dir);
  1408. this._direction = dir;
  1409. }
  1410. return this._direction;
  1411. },
  1412. /**
  1413. Event handler for the Backbone `backgrid:sort` event. Resets this cell's
  1414. direction to default if sorting is being done on another column.
  1415. @private
  1416. */
  1417. _resetCellDirection: function (sortByColName, direction, comparator, collection) {
  1418. if (collection == this.collection) {
  1419. if (sortByColName !== this.column.get("name")) this.direction(null);
  1420. else this.direction(direction);
  1421. }
  1422. },
  1423. /**
  1424. Event handler for the `click` event on the cell's anchor. If the column is
  1425. sortable, clicking on the anchor will cycle through 3 sorting orderings -
  1426. `ascending`, `descending`, and default.
  1427. */
  1428. onClick: function (e) {
  1429. e.preventDefault();
  1430. var columnName = this.column.get("name");
  1431. if (this.column.get("sortable")) {
  1432. if (this.direction() === "ascending") {
  1433. this.sort(columnName, "descending", function (left, right) {

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