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

/backgrid-0.3.5/lib/backgrid.js

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