PageRenderTime 64ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/backgrid.js

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