PageRenderTime 55ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/backgrid.js

https://github.com/TechnotronicOz/backgrid
JavaScript | 2884 lines | 1237 code | 378 blank | 1269 comment | 265 complexity | 5abf4c8cee163d62a9a026452313ee8c MD5 | raw file
Possible License(s): MIT

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

  1. /*!
  2. backgrid 0.3.5
  3. http://github.com/wyuenho/backgrid
  4. Copyright (c) 2014 Jimmy Yuen Ho Wong and contributors <wyuenho@gmail.com>
  5. Licensed under the MIT license.
  6. */
  7. (function (root, factory) {
  8. if (typeof define === "function" && define.amd) {
  9. // AMD (+ global for extensions)
  10. define(["underscore", "backbone"], function (_, Backbone) {
  11. return (root.Backgrid = factory(_, Backbone));
  12. });
  13. } else if (typeof exports === "object") {
  14. // CommonJS
  15. module.exports = factory(require("underscore"), require("backbone"));
  16. } else {
  17. // Browser
  18. root.Backgrid = factory(root._, root.Backbone);
  19. }}(this, function (_, Backbone) {
  20. "use strict";
  21. /*
  22. backgrid
  23. http://github.com/wyuenho/backgrid
  24. Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors
  25. Licensed under the MIT license.
  26. */
  27. // Copyright 2009, 2010 Kristopher Michael Kowal
  28. // https://github.com/kriskowal/es5-shim
  29. // ES5 15.5.4.20
  30. // http://es5.github.com/#x15.5.4.20
  31. var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" +
  32. "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" +
  33. "\u2029\uFEFF";
  34. if (!String.prototype.trim || ws.trim()) {
  35. // http://blog.stevenlevithan.com/archives/faster-trim-javascript
  36. // http://perfectionkills.com/whitespace-deviations/
  37. ws = "[" + ws + "]";
  38. var trimBeginRegexp = new RegExp("^" + ws + ws + "*"),
  39. trimEndRegexp = new RegExp(ws + ws + "*$");
  40. String.prototype.trim = function trim() {
  41. if (this === undefined || this === null) {
  42. throw new TypeError("can't convert " + this + " to object");
  43. }
  44. return String(this)
  45. .replace(trimBeginRegexp, "")
  46. .replace(trimEndRegexp, "");
  47. };
  48. }
  49. function lpad(str, length, padstr) {
  50. var paddingLen = length - (str + '').length;
  51. paddingLen = paddingLen < 0 ? 0 : paddingLen;
  52. var padding = '';
  53. for (var i = 0; i < paddingLen; i++) {
  54. padding = padding + padstr;
  55. }
  56. return padding + str;
  57. }
  58. var $ = Backbone.$;
  59. var Backgrid = {
  60. Extension: {},
  61. resolveNameToClass: function (name, suffix) {
  62. if (_.isString(name)) {
  63. var key = _.map(name.split('-'), function (e) {
  64. return e.slice(0, 1).toUpperCase() + e.slice(1);
  65. }).join('') + suffix;
  66. var klass = Backgrid[key] || Backgrid.Extension[key];
  67. if (_.isUndefined(klass)) {
  68. throw new ReferenceError("Class '" + key + "' not found");
  69. }
  70. return klass;
  71. }
  72. return name;
  73. },
  74. callByNeed: function () {
  75. var value = arguments[0];
  76. if (!_.isFunction(value)) return value;
  77. var context = arguments[1];
  78. var args = [].slice.call(arguments, 2);
  79. return value.apply(context, !!(args + '') ? args : []);
  80. }
  81. };
  82. _.extend(Backgrid, Backbone.Events);
  83. /**
  84. Command translates a DOM Event into commands that Backgrid
  85. recognizes. Interested parties can listen on selected Backgrid events that
  86. come with an instance of this class and act on the commands.
  87. It is also possible to globally rebind the keyboard shortcuts by replacing
  88. the methods in this class' prototype.
  89. @class Backgrid.Command
  90. @constructor
  91. */
  92. var Command = Backgrid.Command = function (evt) {
  93. _.extend(this, {
  94. altKey: !!evt.altKey,
  95. "char": evt["char"],
  96. charCode: evt.charCode,
  97. ctrlKey: !!evt.ctrlKey,
  98. key: evt.key,
  99. keyCode: evt.keyCode,
  100. locale: evt.locale,
  101. location: evt.location,
  102. metaKey: !!evt.metaKey,
  103. repeat: !!evt.repeat,
  104. shiftKey: !!evt.shiftKey,
  105. which: evt.which
  106. });
  107. };
  108. _.extend(Command.prototype, {
  109. /**
  110. Up Arrow
  111. @member Backgrid.Command
  112. */
  113. moveUp: function () { return this.keyCode == 38; },
  114. /**
  115. Down Arrow
  116. @member Backgrid.Command
  117. */
  118. moveDown: function () { return this.keyCode === 40; },
  119. /**
  120. Shift Tab
  121. @member Backgrid.Command
  122. */
  123. moveLeft: function () { return this.shiftKey && this.keyCode === 9; },
  124. /**
  125. Tab
  126. @member Backgrid.Command
  127. */
  128. moveRight: function () { return !this.shiftKey && this.keyCode === 9; },
  129. /**
  130. Enter
  131. @member Backgrid.Command
  132. */
  133. save: function () { return this.keyCode === 13; },
  134. /**
  135. Esc
  136. @member Backgrid.Command
  137. */
  138. cancel: function () { return this.keyCode === 27; },
  139. /**
  140. None of the above.
  141. @member Backgrid.Command
  142. */
  143. passThru: function () {
  144. return !(this.moveUp() || this.moveDown() || this.moveLeft() ||
  145. this.moveRight() || this.save() || this.cancel());
  146. }
  147. });
  148. /*
  149. backgrid
  150. http://github.com/wyuenho/backgrid
  151. Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors
  152. Licensed under the MIT license.
  153. */
  154. /**
  155. Just a convenient class for interested parties to subclass.
  156. The default Cell classes don't require the formatter to be a subclass of
  157. Formatter as long as the fromRaw(rawData) and toRaw(formattedData) methods
  158. are defined.
  159. @abstract
  160. @class Backgrid.CellFormatter
  161. @constructor
  162. */
  163. var CellFormatter = Backgrid.CellFormatter = function () {};
  164. _.extend(CellFormatter.prototype, {
  165. /**
  166. Takes a raw value from a model and returns an optionally formatted string
  167. for display. The default implementation simply returns the supplied value
  168. as is without any type conversion.
  169. @member Backgrid.CellFormatter
  170. @param {*} rawData
  171. @param {Backbone.Model} model Used for more complicated formatting
  172. @return {*}
  173. */
  174. fromRaw: function (rawData, model) {
  175. return rawData;
  176. },
  177. /**
  178. Takes a formatted string, usually from user input, and returns a
  179. appropriately typed value for persistence in the model.
  180. If the user input is invalid or unable to be converted to a raw value
  181. suitable for persistence in the model, toRaw must return `undefined`.
  182. @member Backgrid.CellFormatter
  183. @param {string} formattedData
  184. @param {Backbone.Model} model Used for more complicated formatting
  185. @return {*|undefined}
  186. */
  187. toRaw: function (formattedData, model) {
  188. return formattedData;
  189. }
  190. });
  191. /**
  192. A floating point number formatter. Doesn't understand scientific notation at
  193. the moment.
  194. @class Backgrid.NumberFormatter
  195. @extends Backgrid.CellFormatter
  196. @constructor
  197. @throws {RangeError} If decimals < 0 or > 20.
  198. */
  199. var NumberFormatter = Backgrid.NumberFormatter = function (options) {
  200. _.extend(this, this.defaults, options || {});
  201. if (this.decimals < 0 || this.decimals > 20) {
  202. throw new RangeError("decimals must be between 0 and 20");
  203. }
  204. };
  205. NumberFormatter.prototype = new CellFormatter();
  206. _.extend(NumberFormatter.prototype, {
  207. /**
  208. @member Backgrid.NumberFormatter
  209. @cfg {Object} options
  210. @cfg {number} [options.decimals=2] Number of decimals to display. Must be an integer.
  211. @cfg {string} [options.decimalSeparator='.'] The separator to use when
  212. displaying decimals.
  213. @cfg {string} [options.orderSeparator=','] The separator to use to
  214. separator thousands. May be an empty string.
  215. */
  216. defaults: {
  217. decimals: 2,
  218. decimalSeparator: '.',
  219. orderSeparator: ','
  220. },
  221. HUMANIZED_NUM_RE: /(\d)(?=(?:\d{3})+$)/g,
  222. /**
  223. Takes a floating point number and convert it to a formatted string where
  224. every thousand is separated by `orderSeparator`, with a `decimal` number of
  225. decimals separated by `decimalSeparator`. The number returned is rounded
  226. the usual way.
  227. @member Backgrid.NumberFormatter
  228. @param {number} number
  229. @param {Backbone.Model} model Used for more complicated formatting
  230. @return {string}
  231. */
  232. fromRaw: function (number, model) {
  233. if (_.isNull(number) || _.isUndefined(number)) return '';
  234. number = number.toFixed(~~this.decimals);
  235. var parts = number.split('.');
  236. var integerPart = parts[0];
  237. var decimalPart = parts[1] ? (this.decimalSeparator || '.') + parts[1] : '';
  238. return integerPart.replace(this.HUMANIZED_NUM_RE, '$1' + this.orderSeparator) + decimalPart;
  239. },
  240. /**
  241. Takes a string, possibly formatted with `orderSeparator` and/or
  242. `decimalSeparator`, and convert it back to a number.
  243. @member Backgrid.NumberFormatter
  244. @param {string} formattedData
  245. @param {Backbone.Model} model Used for more complicated formatting
  246. @return {number|undefined} Undefined if the string cannot be converted to
  247. a number.
  248. */
  249. toRaw: function (formattedData, model) {
  250. formattedData = formattedData.trim();
  251. if (formattedData === '') return null;
  252. var rawData = '';
  253. var thousands = formattedData.split(this.orderSeparator);
  254. for (var i = 0; i < thousands.length; i++) {
  255. rawData += thousands[i];
  256. }
  257. var decimalParts = rawData.split(this.decimalSeparator);
  258. rawData = '';
  259. for (var i = 0; i < decimalParts.length; i++) {
  260. rawData = rawData + decimalParts[i] + '.';
  261. }
  262. if (rawData[rawData.length - 1] === '.') {
  263. rawData = rawData.slice(0, rawData.length - 1);
  264. }
  265. var result = (rawData * 1).toFixed(~~this.decimals) * 1;
  266. if (_.isNumber(result) && !_.isNaN(result)) return result;
  267. }
  268. });
  269. /**
  270. A number formatter that converts a floating point number, optionally
  271. multiplied by a multiplier, to a percentage string and vice versa.
  272. @class Backgrid.PercentFormatter
  273. @extends Backgrid.NumberFormatter
  274. @constructor
  275. @throws {RangeError} If decimals < 0 or > 20.
  276. */
  277. var PercentFormatter = Backgrid.PercentFormatter = function () {
  278. Backgrid.NumberFormatter.apply(this, arguments);
  279. };
  280. PercentFormatter.prototype = new Backgrid.NumberFormatter(),
  281. _.extend(PercentFormatter.prototype, {
  282. /**
  283. @member Backgrid.PercentFormatter
  284. @cfg {Object} options
  285. @cfg {number} [options.multiplier=1] The number used to multiply the model
  286. value for display.
  287. @cfg {string} [options.symbol='%'] The symbol to append to the percentage
  288. string.
  289. */
  290. defaults: _.extend({}, NumberFormatter.prototype.defaults, {
  291. multiplier: 1,
  292. symbol: "%"
  293. }),
  294. /**
  295. Takes a floating point number, where the number is first multiplied by
  296. `multiplier`, then converted to a formatted string like
  297. NumberFormatter#fromRaw, then finally append `symbol` to the end.
  298. @member Backgrid.PercentFormatter
  299. @param {number} rawValue
  300. @param {Backbone.Model} model Used for more complicated formatting
  301. @return {string}
  302. */
  303. fromRaw: function (number, model) {
  304. var args = [].slice.call(arguments, 1);
  305. args.unshift(number * this.multiplier);
  306. return (NumberFormatter.prototype.fromRaw.apply(this, args) || "0") + this.symbol;
  307. },
  308. /**
  309. Takes a string, possibly appended with `symbol` and/or `decimalSeparator`,
  310. and convert it back to a number for the model like NumberFormatter#toRaw,
  311. and then dividing it by `multiplier`.
  312. @member Backgrid.PercentFormatter
  313. @param {string} formattedData
  314. @param {Backbone.Model} model Used for more complicated formatting
  315. @return {number|undefined} Undefined if the string cannot be converted to
  316. a number.
  317. */
  318. toRaw: function (formattedValue, model) {
  319. var tokens = formattedValue.split(this.symbol);
  320. if (tokens && tokens[0] && tokens[1] === "" || tokens[1] == null) {
  321. var rawValue = NumberFormatter.prototype.toRaw.call(this, tokens[0]);
  322. if (_.isUndefined(rawValue)) return rawValue;
  323. return rawValue / this.multiplier;
  324. }
  325. }
  326. });
  327. /**
  328. Formatter to converts between various datetime formats.
  329. This class only understands ISO-8601 formatted datetime strings and UNIX
  330. offset (number of milliseconds since UNIX Epoch). See
  331. Backgrid.Extension.MomentFormatter if you need a much more flexible datetime
  332. formatter.
  333. @class Backgrid.DatetimeFormatter
  334. @extends Backgrid.CellFormatter
  335. @constructor
  336. @throws {Error} If both `includeDate` and `includeTime` are false.
  337. */
  338. var DatetimeFormatter = Backgrid.DatetimeFormatter = function (options) {
  339. _.extend(this, this.defaults, options || {});
  340. if (!this.includeDate && !this.includeTime) {
  341. throw new Error("Either includeDate or includeTime must be true");
  342. }
  343. };
  344. DatetimeFormatter.prototype = new CellFormatter();
  345. _.extend(DatetimeFormatter.prototype, {
  346. /**
  347. @member Backgrid.DatetimeFormatter
  348. @cfg {Object} options
  349. @cfg {boolean} [options.includeDate=true] Whether the values include the
  350. date part.
  351. @cfg {boolean} [options.includeTime=true] Whether the values include the
  352. time part.
  353. @cfg {boolean} [options.includeMilli=false] If `includeTime` is true,
  354. whether to include the millisecond part, if it exists.
  355. */
  356. defaults: {
  357. includeDate: true,
  358. includeTime: true,
  359. includeMilli: false
  360. },
  361. DATE_RE: /^([+\-]?\d{4})-(\d{2})-(\d{2})$/,
  362. TIME_RE: /^(\d{2}):(\d{2}):(\d{2})(\.(\d{3}))?$/,
  363. ISO_SPLITTER_RE: /T|Z| +/,
  364. _convert: function (data, validate) {
  365. if ((data + '').trim() === '') return null;
  366. var date, time = null;
  367. if (_.isNumber(data)) {
  368. var jsDate = new Date(data);
  369. date = lpad(jsDate.getUTCFullYear(), 4, 0) + '-' + lpad(jsDate.getUTCMonth() + 1, 2, 0) + '-' + lpad(jsDate.getUTCDate(), 2, 0);
  370. time = lpad(jsDate.getUTCHours(), 2, 0) + ':' + lpad(jsDate.getUTCMinutes(), 2, 0) + ':' + lpad(jsDate.getUTCSeconds(), 2, 0);
  371. }
  372. else {
  373. data = data.trim();
  374. var parts = data.split(this.ISO_SPLITTER_RE) || [];
  375. date = this.DATE_RE.test(parts[0]) ? parts[0] : '';
  376. time = date && parts[1] ? parts[1] : this.TIME_RE.test(parts[0]) ? parts[0] : '';
  377. }
  378. var YYYYMMDD = this.DATE_RE.exec(date) || [];
  379. var HHmmssSSS = this.TIME_RE.exec(time) || [];
  380. if (validate) {
  381. if (this.includeDate && _.isUndefined(YYYYMMDD[0])) return;
  382. if (this.includeTime && _.isUndefined(HHmmssSSS[0])) return;
  383. if (!this.includeDate && date) return;
  384. if (!this.includeTime && time) return;
  385. }
  386. var jsDate = new Date(Date.UTC(YYYYMMDD[1] * 1 || 0,
  387. YYYYMMDD[2] * 1 - 1 || 0,
  388. YYYYMMDD[3] * 1 || 0,
  389. HHmmssSSS[1] * 1 || null,
  390. HHmmssSSS[2] * 1 || null,
  391. HHmmssSSS[3] * 1 || null,
  392. HHmmssSSS[5] * 1 || null));
  393. var result = '';
  394. if (this.includeDate) {
  395. result = lpad(jsDate.getUTCFullYear(), 4, 0) + '-' + lpad(jsDate.getUTCMonth() + 1, 2, 0) + '-' + lpad(jsDate.getUTCDate(), 2, 0);
  396. }
  397. if (this.includeTime) {
  398. result = result + (this.includeDate ? 'T' : '') + lpad(jsDate.getUTCHours(), 2, 0) + ':' + lpad(jsDate.getUTCMinutes(), 2, 0) + ':' + lpad(jsDate.getUTCSeconds(), 2, 0);
  399. if (this.includeMilli) {
  400. result = result + '.' + lpad(jsDate.getUTCMilliseconds(), 3, 0);
  401. }
  402. }
  403. if (this.includeDate && this.includeTime) {
  404. result += "Z";
  405. }
  406. return result;
  407. },
  408. /**
  409. Converts an ISO-8601 formatted datetime string to a datetime string, date
  410. string or a time string. The timezone is ignored if supplied.
  411. @member Backgrid.DatetimeFormatter
  412. @param {string} rawData
  413. @param {Backbone.Model} model Used for more complicated formatting
  414. @return {string|null|undefined} ISO-8601 string in UTC. Null and undefined
  415. values are returned as is.
  416. */
  417. fromRaw: function (rawData, model) {
  418. if (_.isNull(rawData) || _.isUndefined(rawData)) return '';
  419. return this._convert(rawData);
  420. },
  421. /**
  422. Converts an ISO-8601 formatted datetime string to a datetime string, date
  423. string or a time string. The timezone is ignored if supplied. This method
  424. parses the input values exactly the same way as
  425. Backgrid.Extension.MomentFormatter#fromRaw(), in addition to doing some
  426. sanity checks.
  427. @member Backgrid.DatetimeFormatter
  428. @param {string} formattedData
  429. @param {Backbone.Model} model Used for more complicated formatting
  430. @return {string|undefined} ISO-8601 string in UTC. Undefined if a date is
  431. found when `includeDate` is false, or a time is found when `includeTime` is
  432. false, or if `includeDate` is true and a date is not found, or if
  433. `includeTime` is true and a time is not found.
  434. */
  435. toRaw: function (formattedData, model) {
  436. return this._convert(formattedData, true);
  437. }
  438. });
  439. /**
  440. Formatter to convert any value to string.
  441. @class Backgrid.StringFormatter
  442. @extends Backgrid.CellFormatter
  443. @constructor
  444. */
  445. var StringFormatter = Backgrid.StringFormatter = function () {};
  446. StringFormatter.prototype = new CellFormatter();
  447. _.extend(StringFormatter.prototype, {
  448. /**
  449. Converts any value to a string using Ecmascript's implicit type
  450. conversion. If the given value is `null` or `undefined`, an empty string is
  451. returned instead.
  452. @member Backgrid.StringFormatter
  453. @param {*} rawValue
  454. @param {Backbone.Model} model Used for more complicated formatting
  455. @return {string}
  456. */
  457. fromRaw: function (rawValue, model) {
  458. if (_.isUndefined(rawValue) || _.isNull(rawValue)) return '';
  459. return rawValue + '';
  460. }
  461. });
  462. /**
  463. Simple email validation formatter.
  464. @class Backgrid.EmailFormatter
  465. @extends Backgrid.CellFormatter
  466. @constructor
  467. */
  468. var EmailFormatter = Backgrid.EmailFormatter = function () {};
  469. EmailFormatter.prototype = new CellFormatter();
  470. _.extend(EmailFormatter.prototype, {
  471. /**
  472. Return the input if it is a string that contains an '@' character and if
  473. the strings before and after '@' are non-empty. If the input does not
  474. validate, `undefined` is returned.
  475. @member Backgrid.EmailFormatter
  476. @param {*} formattedData
  477. @param {Backbone.Model} model Used for more complicated formatting
  478. @return {string|undefined}
  479. */
  480. toRaw: function (formattedData, model) {
  481. var parts = formattedData.trim().split("@");
  482. if (parts.length === 2 && _.all(parts)) {
  483. return formattedData;
  484. }
  485. }
  486. });
  487. /**
  488. Formatter for SelectCell.
  489. If the type of a model value is not a string, it is expected that a subclass
  490. of this formatter is provided to the SelectCell, with #toRaw overridden to
  491. convert the string value returned from the DOM back to whatever value is
  492. expected in the model.
  493. @class Backgrid.SelectFormatter
  494. @extends Backgrid.CellFormatter
  495. @constructor
  496. */
  497. var SelectFormatter = Backgrid.SelectFormatter = function () {};
  498. SelectFormatter.prototype = new CellFormatter();
  499. _.extend(SelectFormatter.prototype, {
  500. /**
  501. Normalizes raw scalar or array values to an array.
  502. @member Backgrid.SelectFormatter
  503. @param {*} rawValue
  504. @param {Backbone.Model} model Used for more complicated formatting
  505. @return {Array.<*>}
  506. */
  507. fromRaw: function (rawValue, model) {
  508. return _.isArray(rawValue) ? rawValue : rawValue != null ? [rawValue] : [];
  509. }
  510. });
  511. /*
  512. backgrid
  513. http://github.com/wyuenho/backgrid
  514. Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors
  515. Licensed under the MIT license.
  516. */
  517. /**
  518. Generic cell editor base class. Only defines an initializer for a number of
  519. required parameters.
  520. @abstract
  521. @class Backgrid.CellEditor
  522. @extends Backbone.View
  523. */
  524. var CellEditor = Backgrid.CellEditor = Backbone.View.extend({
  525. /**
  526. Initializer.
  527. @param {Object} options
  528. @param {Backgrid.CellFormatter} options.formatter
  529. @param {Backgrid.Column} options.column
  530. @param {Backbone.Model} options.model
  531. @throws {TypeError} If `formatter` is not a formatter instance, or when
  532. `model` or `column` are undefined.
  533. */
  534. initialize: function (options) {
  535. this.formatter = options.formatter;
  536. this.column = options.column;
  537. if (!(this.column instanceof Column)) {
  538. this.column = new Column(this.column);
  539. }
  540. this.listenTo(this.model, "backgrid:editing", this.postRender);
  541. },
  542. /**
  543. Post-rendering setup and initialization. Focuses the cell editor's `el` in
  544. this default implementation. **Should** be called by Cell classes after
  545. calling Backgrid.CellEditor#render.
  546. */
  547. postRender: function (model, column) {
  548. if (column == null || column.get("name") == this.column.get("name")) {
  549. this.$el.focus();
  550. }
  551. return this;
  552. }
  553. });
  554. /**
  555. InputCellEditor the cell editor type used by most core cell types. This cell
  556. editor renders a text input box as its editor. The input will render a
  557. placeholder if the value is empty on supported browsers.
  558. @class Backgrid.InputCellEditor
  559. @extends Backgrid.CellEditor
  560. */
  561. var InputCellEditor = Backgrid.InputCellEditor = CellEditor.extend({
  562. /** @property */
  563. tagName: "input",
  564. /** @property */
  565. attributes: {
  566. type: "text"
  567. },
  568. /** @property */
  569. events: {
  570. "blur": "saveOrCancel",
  571. "keydown": "saveOrCancel"
  572. },
  573. /**
  574. Initializer. Removes this `el` from the DOM when a `done` event is
  575. triggered.
  576. @param {Object} options
  577. @param {Backgrid.CellFormatter} options.formatter
  578. @param {Backgrid.Column} options.column
  579. @param {Backbone.Model} options.model
  580. @param {string} [options.placeholder]
  581. */
  582. initialize: function (options) {
  583. InputCellEditor.__super__.initialize.apply(this, arguments);
  584. if (options.placeholder) {
  585. this.$el.attr("placeholder", options.placeholder);
  586. }
  587. },
  588. /**
  589. Renders a text input with the cell value formatted for display, if it
  590. exists.
  591. */
  592. render: function () {
  593. var model = this.model;
  594. this.$el.val(this.formatter.fromRaw(model.get(this.column.get("name")), model));
  595. return this;
  596. },
  597. /**
  598. If the key pressed is `enter`, `tab`, `up`, or `down`, converts the value
  599. in the editor to a raw value for saving into the model using the formatter.
  600. If the key pressed is `esc` the changes are undone.
  601. If the editor goes out of focus (`blur`) but the value is invalid, the
  602. event is intercepted and cancelled so the cell remains in focus pending for
  603. further action. The changes are saved otherwise.
  604. Triggers a Backbone `backgrid:edited` event from the model when successful,
  605. and `backgrid:error` if the value cannot be converted. Classes listening to
  606. the `error` event, usually the Cell classes, should respond appropriately,
  607. usually by rendering some kind of error feedback.
  608. @param {Event} e
  609. */
  610. saveOrCancel: function (e) {
  611. var formatter = this.formatter;
  612. var model = this.model;
  613. var column = this.column;
  614. var command = new Command(e);
  615. var blurred = e.type === "blur";
  616. if (command.moveUp() || command.moveDown() || command.moveLeft() || command.moveRight() ||
  617. command.save() || blurred) {
  618. e.preventDefault();
  619. e.stopPropagation();
  620. var val = this.$el.val();
  621. var newValue = formatter.toRaw(val, model);
  622. if (_.isUndefined(newValue)) {
  623. model.trigger("backgrid:error", model, column, val);
  624. }
  625. else {
  626. model.set(column.get("name"), newValue);
  627. model.trigger("backgrid:edited", model, column, command);
  628. }
  629. }
  630. // esc
  631. else if (command.cancel()) {
  632. // undo
  633. e.stopPropagation();
  634. model.trigger("backgrid:edited", model, column, command);
  635. }
  636. },
  637. postRender: function (model, column) {
  638. if (column == null || column.get("name") == this.column.get("name")) {
  639. // move the cursor to the end on firefox if text is right aligned
  640. if (this.$el.css("text-align") === "right") {
  641. var val = this.$el.val();
  642. this.$el.focus().val(null).val(val);
  643. }
  644. else this.$el.focus();
  645. }
  646. return this;
  647. }
  648. });
  649. /**
  650. The super-class for all Cell types. By default, this class renders a plain
  651. table cell with the model value converted to a string using the
  652. formatter. The table cell is clickable, upon which the cell will go into
  653. editor mode, which is rendered by a Backgrid.InputCellEditor instance by
  654. default. Upon encountering any formatting errors, this class will add an
  655. `error` CSS class to the table cell.
  656. @abstract
  657. @class Backgrid.Cell
  658. @extends Backbone.View
  659. */
  660. var Cell = Backgrid.Cell = Backbone.View.extend({
  661. /** @property */
  662. tagName: "td",
  663. /**
  664. @property {Backgrid.CellFormatter|Object|string} [formatter=CellFormatter]
  665. */
  666. formatter: CellFormatter,
  667. /**
  668. @property {Backgrid.CellEditor} [editor=Backgrid.InputCellEditor] The
  669. default editor for all cell instances of this class. This value must be a
  670. class, it will be automatically instantiated upon entering edit mode.
  671. See Backgrid.CellEditor
  672. */
  673. editor: InputCellEditor,
  674. /** @property */
  675. events: {
  676. "click": "enterEditMode"
  677. },
  678. /**
  679. Initializer.
  680. @param {Object} options
  681. @param {Backbone.Model} options.model
  682. @param {Backgrid.Column} options.column
  683. @throws {ReferenceError} If formatter is a string but a formatter class of
  684. said name cannot be found in the Backgrid module.
  685. */
  686. initialize: function (options) {
  687. this.column = options.column;
  688. if (!(this.column instanceof Column)) {
  689. this.column = new Column(this.column);
  690. }
  691. var column = this.column, model = this.model, $el = this.$el;
  692. var formatter = Backgrid.resolveNameToClass(column.get("formatter") ||
  693. this.formatter, "Formatter");
  694. if (!_.isFunction(formatter.fromRaw) && !_.isFunction(formatter.toRaw)) {
  695. formatter = new formatter();
  696. }
  697. this.formatter = formatter;
  698. this.editor = Backgrid.resolveNameToClass(this.editor, "CellEditor");
  699. this.listenTo(model, "change:" + column.get("name"), function () {
  700. if (!$el.hasClass("editor")) this.render();
  701. });
  702. this.listenTo(model, "backgrid:error", this.renderError);
  703. this.listenTo(column, "change:editable change:sortable change:renderable",
  704. function (column) {
  705. var changed = column.changedAttributes();
  706. for (var key in changed) {
  707. if (changed.hasOwnProperty(key)) {
  708. $el.toggleClass(key, changed[key]);
  709. }
  710. }
  711. });
  712. if (Backgrid.callByNeed(column.editable(), column, model)) $el.addClass("editable");
  713. if (Backgrid.callByNeed(column.sortable(), column, model)) $el.addClass("sortable");
  714. if (Backgrid.callByNeed(column.renderable(), column, model)) $el.addClass("renderable");
  715. },
  716. /**
  717. Render a text string in a table cell. The text is converted from the
  718. model's raw value for this cell's column.
  719. */
  720. render: function () {
  721. this.$el.empty();
  722. var model = this.model;
  723. this.$el.text(this.formatter.fromRaw(model.get(this.column.get("name")), model));
  724. this.delegateEvents();
  725. return this;
  726. },
  727. /**
  728. If this column is editable, a new CellEditor instance is instantiated with
  729. its required parameters. An `editor` CSS class is added to the cell upon
  730. entering edit mode.
  731. This method triggers a Backbone `backgrid:edit` event from the model when
  732. the cell is entering edit mode and an editor instance has been constructed,
  733. but before it is rendered and inserted into the DOM. The cell and the
  734. constructed cell editor instance are sent as event parameters when this
  735. event is triggered.
  736. When this cell has finished switching to edit mode, a Backbone
  737. `backgrid:editing` event is triggered from the model. The cell and the
  738. constructed cell instance are also sent as parameters in the event.
  739. When the model triggers a `backgrid:error` event, it means the editor is
  740. unable to convert the current user input to an apprpriate value for the
  741. model's column, and an `error` CSS class is added to the cell accordingly.
  742. */
  743. enterEditMode: function () {
  744. var model = this.model;
  745. var column = this.column;
  746. var editable = Backgrid.callByNeed(column.editable(), column, model);
  747. if (editable) {
  748. this.currentEditor = new this.editor({
  749. column: this.column,
  750. model: this.model,
  751. formatter: this.formatter
  752. });
  753. model.trigger("backgrid:edit", model, column, this, this.currentEditor);
  754. // Need to redundantly undelegate events for Firefox
  755. this.undelegateEvents();
  756. this.$el.empty();
  757. this.$el.append(this.currentEditor.$el);
  758. this.currentEditor.render();
  759. this.$el.addClass("editor");
  760. model.trigger("backgrid:editing", model, column, this, this.currentEditor);
  761. }
  762. },
  763. /**
  764. Put an `error` CSS class on the table cell.
  765. */
  766. renderError: function (model, column) {
  767. if (column == null || column.get("name") == this.column.get("name")) {
  768. this.$el.addClass("error");
  769. }
  770. },
  771. /**
  772. Removes the editor and re-render in display mode.
  773. */
  774. exitEditMode: function () {
  775. this.$el.removeClass("error");
  776. this.currentEditor.remove();
  777. this.stopListening(this.currentEditor);
  778. delete this.currentEditor;
  779. this.$el.removeClass("editor");
  780. this.render();
  781. },
  782. /**
  783. Clean up this cell.
  784. @chainable
  785. */
  786. remove: function () {
  787. if (this.currentEditor) {
  788. this.currentEditor.remove.apply(this.currentEditor, arguments);
  789. delete this.currentEditor;
  790. }
  791. return Cell.__super__.remove.apply(this, arguments);
  792. }
  793. });
  794. /**
  795. StringCell displays HTML escaped strings and accepts anything typed in.
  796. @class Backgrid.StringCell
  797. @extends Backgrid.Cell
  798. */
  799. var StringCell = Backgrid.StringCell = Cell.extend({
  800. /** @property */
  801. className: "string-cell",
  802. formatter: StringFormatter
  803. });
  804. /**
  805. UriCell renders an HTML `<a>` anchor for the value and accepts URIs as user
  806. input values. No type conversion or URL validation is done by the formatter
  807. of this cell. Users who need URL validation are encourage to subclass UriCell
  808. to take advantage of the parsing capabilities of the HTMLAnchorElement
  809. available on HTML5-capable browsers or using a third-party library like
  810. [URI.js](https://github.com/medialize/URI.js).
  811. @class Backgrid.UriCell
  812. @extends Backgrid.Cell
  813. */
  814. var UriCell = Backgrid.UriCell = Cell.extend({
  815. /** @property */
  816. className: "uri-cell",
  817. /**
  818. @property {string} [title] The title attribute of the generated anchor. It
  819. uses the display value formatted by the `formatter.fromRaw` by default.
  820. */
  821. title: null,
  822. /**
  823. @property {string} [target="_blank"] The target attribute of the generated
  824. anchor.
  825. */
  826. target: "_blank",
  827. initialize: function (options) {
  828. UriCell.__super__.initialize.apply(this, arguments);
  829. this.title = options.title || this.title;
  830. this.target = options.target || this.target;
  831. },
  832. render: function () {
  833. this.$el.empty();
  834. var rawValue = this.model.get(this.column.get("name"));
  835. var formattedValue = this.formatter.fromRaw(rawValue, this.model);
  836. this.$el.append($("<a>", {
  837. tabIndex: -1,
  838. href: rawValue,
  839. title: this.title || formattedValue,
  840. target: this.target
  841. }).text(formattedValue));
  842. this.delegateEvents();
  843. return this;
  844. }
  845. });
  846. /**
  847. Like Backgrid.UriCell, EmailCell renders an HTML `<a>` anchor for the
  848. value. The `href` in the anchor is prefixed with `mailto:`. EmailCell will
  849. complain if the user enters a string that doesn't contain the `@` sign.
  850. @class Backgrid.EmailCell
  851. @extends Backgrid.StringCell
  852. */
  853. var EmailCell = Backgrid.EmailCell = StringCell.extend({
  854. /** @property */
  855. className: "email-cell",
  856. formatter: EmailFormatter,
  857. render: function () {
  858. this.$el.empty();
  859. var model = this.model;
  860. var formattedValue = this.formatter.fromRaw(model.get(this.column.get("name")), model);
  861. this.$el.append($("<a>", {
  862. tabIndex: -1,
  863. href: "mailto:" + formattedValue,
  864. title: formattedValue
  865. }).text(formattedValue));
  866. this.delegateEvents();
  867. return this;
  868. }
  869. });
  870. /**
  871. NumberCell is a generic cell that renders all numbers. Numbers are formatted
  872. using a Backgrid.NumberFormatter.
  873. @class Backgrid.NumberCell
  874. @extends Backgrid.Cell
  875. */
  876. var NumberCell = Backgrid.NumberCell = Cell.extend({
  877. /** @property */
  878. className: "number-cell",
  879. /**
  880. @property {number} [decimals=2] Must be an integer.
  881. */
  882. decimals: NumberFormatter.prototype.defaults.decimals,
  883. /** @property {string} [decimalSeparator='.'] */
  884. decimalSeparator: NumberFormatter.prototype.defaults.decimalSeparator,
  885. /** @property {string} [orderSeparator=','] */
  886. orderSeparator: NumberFormatter.prototype.defaults.orderSeparator,
  887. /** @property {Backgrid.CellFormatter} [formatter=Backgrid.NumberFormatter] */
  888. formatter: NumberFormatter,
  889. /**
  890. Initializes this cell and the number formatter.
  891. @param {Object} options
  892. @param {Backbone.Model} options.model
  893. @param {Backgrid.Column} options.column
  894. */
  895. initialize: function (options) {
  896. NumberCell.__super__.initialize.apply(this, arguments);
  897. var formatter = this.formatter;
  898. formatter.decimals = this.decimals;
  899. formatter.decimalSeparator = this.decimalSeparator;
  900. formatter.orderSeparator = this.orderSeparator;
  901. }
  902. });
  903. /**
  904. An IntegerCell is just a Backgrid.NumberCell with 0 decimals. If a floating
  905. point number is supplied, the number is simply rounded the usual way when
  906. displayed.
  907. @class Backgrid.IntegerCell
  908. @extends Backgrid.NumberCell
  909. */
  910. var IntegerCell = Backgrid.IntegerCell = NumberCell.extend({
  911. /** @property */
  912. className: "integer-cell",
  913. /**
  914. @property {number} decimals Must be an integer.
  915. */
  916. decimals: 0
  917. });
  918. /**
  919. A PercentCell is another Backgrid.NumberCell that takes a floating number,
  920. optionally multiplied by a multiplier and display it as a percentage.
  921. @class Backgrid.PercentCell
  922. @extends Backgrid.NumberCell
  923. */
  924. var PercentCell = Backgrid.PercentCell = NumberCell.extend({
  925. /** @property */
  926. className: "percent-cell",
  927. /** @property {number} [multiplier=1] */
  928. multiplier: PercentFormatter.prototype.defaults.multiplier,
  929. /** @property {string} [symbol='%'] */
  930. symbol: PercentFormatter.prototype.defaults.symbol,
  931. /** @property {Backgrid.CellFormatter} [formatter=Backgrid.PercentFormatter] */
  932. formatter: PercentFormatter,
  933. /**
  934. Initializes this cell and the percent formatter.
  935. @param {Object} options
  936. @param {Backbone.Model} options.model
  937. @param {Backgrid.Column} options.column
  938. */
  939. initialize: function () {
  940. PercentCell.__super__.initialize.apply(this, arguments);
  941. var formatter = this.formatter;
  942. formatter.multiplier = this.multiplier;
  943. formatter.symbol = this.symbol;
  944. }
  945. });
  946. /**
  947. DatetimeCell is a basic cell that accepts datetime string values in RFC-2822
  948. or W3C's subset of ISO-8601 and displays them in ISO-8601 format. For a much
  949. more sophisticated date time cell with better datetime formatting, take a
  950. look at the Backgrid.Extension.MomentCell extension.
  951. @class Backgrid.DatetimeCell
  952. @extends Backgrid.Cell
  953. See:
  954. - Backgrid.Extension.MomentCell
  955. - Backgrid.DatetimeFormatter
  956. */
  957. var DatetimeCell = Backgrid.DatetimeCell = Cell.extend({
  958. /** @property */
  959. className: "datetime-cell",
  960. /**
  961. @property {boolean} [includeDate=true]
  962. */
  963. includeDate: DatetimeFormatter.prototype.defaults.includeDate,
  964. /**
  965. @property {boolean} [includeTime=true]
  966. */
  967. includeTime: DatetimeFormatter.prototype.defaults.includeTime,
  968. /**
  969. @property {boolean} [includeMilli=false]
  970. */
  971. includeMilli: DatetimeFormatter.prototype.defaults.includeMilli,
  972. /** @property {Backgrid.CellFormatter} [formatter=Backgrid.DatetimeFormatter] */
  973. formatter: DatetimeFormatter,
  974. /**
  975. Initializes this cell and the datetime formatter.
  976. @param {Object} options
  977. @param {Backbone.Model} options.model
  978. @param {Backgrid.Column} options.column
  979. */
  980. initialize: function (options) {
  981. DatetimeCell.__super__.initialize.apply(this, arguments);
  982. var formatter = this.formatter;
  983. formatter.includeDate = this.includeDate;
  984. formatter.includeTime = this.includeTime;
  985. formatter.includeMilli = this.includeMilli;
  986. var placeholder = this.includeDate ? "YYYY-MM-DD" : "";
  987. placeholder += (this.includeDate && this.includeTime) ? "T" : "";
  988. placeholder += this.includeTime ? "HH:mm:ss" : "";
  989. placeholder += (this.includeTime && this.includeMilli) ? ".SSS" : "";
  990. this.editor = this.editor.extend({
  991. attributes: _.extend({}, this.editor.prototype.attributes, this.editor.attributes, {
  992. placeholder: placeholder
  993. })
  994. });
  995. }
  996. });
  997. /**
  998. DateCell is a Backgrid.DatetimeCell without the time part.
  999. @class Backgrid.DateCell
  1000. @extends Backgrid.DatetimeCell
  1001. */
  1002. var DateCell = Backgrid.DateCell = DatetimeCell.extend({
  1003. /** @property */
  1004. className: "date-cell",
  1005. /** @property */
  1006. includeTime: false
  1007. });
  1008. /**
  1009. TimeCell is a Backgrid.DatetimeCell without the date part.
  1010. @class Backgrid.TimeCell
  1011. @extends Backgrid.DatetimeCell
  1012. */
  1013. var TimeCell = Backgrid.TimeCell = DatetimeCell.extend({
  1014. /** @property */
  1015. className: "time-cell",
  1016. /** @property */
  1017. includeDate: false
  1018. });
  1019. /**
  1020. BooleanCellEditor renders a checkbox as its editor.
  1021. @class Backgrid.BooleanCellEditor
  1022. @extends Backgrid.CellEditor
  1023. */
  1024. var BooleanCellEditor = Backgrid.BooleanCellEditor = CellEditor.extend({
  1025. /** @property */
  1026. tagName: "input",
  1027. /** @property */
  1028. attributes: {
  1029. tabIndex: -1,
  1030. type: "checkbox"
  1031. },
  1032. /** @property */
  1033. events: {
  1034. "mousedown": function () {
  1035. this.mouseDown = true;
  1036. },
  1037. "blur": "enterOrExitEditMode",
  1038. "mouseup": function () {
  1039. this.mouseDown = false;
  1040. },
  1041. "change": "saveOrCancel",
  1042. "keydown": "saveOrCancel"
  1043. },
  1044. /**
  1045. Renders a checkbox and check it if the model value of this column is true,
  1046. uncheck otherwise.
  1047. */
  1048. render: function () {
  1049. var model = this.model;
  1050. var val = this.formatter.fromRaw(model.get(this.column.get("name")), model);
  1051. this.$el.prop("checked", val);
  1052. return this;
  1053. },
  1054. /**
  1055. Event handler. Hack to deal with the case where `blur` is fired before
  1056. `change` and `click` on a checkbox.
  1057. */
  1058. enterOrExitEditMode: function (e) {
  1059. if (!this.mouseDown) {
  1060. var model = this.model;
  1061. model.trigger("backgrid:edited", model, this.column, new Command(e));
  1062. }
  1063. },
  1064. /**
  1065. Event handler. Save the value into the model if the event is `change` or
  1066. one of the keyboard navigation key presses. Exit edit mode without saving
  1067. if `escape` was pressed.
  1068. */
  1069. saveOrCancel: function (e) {
  1070. var model = this.model;
  1071. var column = this.column;
  1072. var formatter = this.formatter;
  1073. var command = new Command(e);
  1074. // skip ahead to `change` when space is pressed
  1075. if (command.passThru() && e.type != "change") return true;
  1076. if (command.cancel()) {
  1077. e.stopPropagation();
  1078. model.trigger("backgrid:edited", model, column, command);
  1079. }
  1080. var $el = this.$el;
  1081. if (command.save() || command.moveLeft() || command.moveRight() || command.moveUp() ||
  1082. command.moveDown()) {
  1083. e.preventDefault();
  1084. e.stopPropagation();
  1085. var val = formatter.toRaw($el.prop("checked"), model);
  1086. model.set(column.get("name"), val);
  1087. model.trigger("backgrid:edited", model, column, command);
  1088. }
  1089. else if (e.type == "change") {
  1090. var val = formatter.toRaw($el.prop("checked"), model);
  1091. model.set(column.get("name"), val);
  1092. $el.focus();
  1093. }
  1094. }
  1095. });
  1096. /**
  1097. BooleanCell renders a checkbox both during display mode and edit mode. The
  1098. checkbox is checked if the model value is true, unchecked otherwise.
  1099. @class Backgrid.BooleanCell
  1100. @extends Backgrid.Cell
  1101. */
  1102. var BooleanCell = Backgrid.BooleanCell = Cell.extend({
  1103. /** @property */
  1104. className: "boolean-cell",
  1105. /** @property */
  1106. editor: BooleanCellEditor,
  1107. /** @property */
  1108. events: {
  1109. "click": "enterEditMode"
  1110. },
  1111. /**
  1112. Renders a checkbox and check it if the model value of this column is true,
  1113. uncheck otherwise.
  1114. */
  1115. render: function () {
  1116. this.$el.empty();
  1117. var model = this.model, column = this.column;
  1118. var editable = Backgrid.callByNeed(column.editable(), column, model);
  1119. this.$el.append($("<input>", {
  1120. tabIndex: -1,
  1121. type: "checkbox",
  1122. checked: this.formatter.fromRaw(model.get(column.get("name")), model),
  1123. disabled: !editable
  1124. }));
  1125. this.delegateEvents();
  1126. return this;
  1127. }
  1128. });
  1129. /**
  1130. SelectCellEditor renders an HTML `<select>` fragment as the editor.
  1131. @class Backgrid.SelectCellEditor
  1132. @extends Backgrid.CellEditor
  1133. */
  1134. var SelectCellEditor = Backgrid.SelectCellEditor = CellEditor.extend({
  1135. /** @property */
  1136. tagName: "select",
  1137. /** @property */
  1138. events: {
  1139. "change": "save",
  1140. "blur": "close",
  1141. "keydown": "close"
  1142. },
  1143. /** @property {function(Object, ?Object=): string} template */
  1144. template: _.template('<option value="<%- value %>" <%= selected ? \'selected="selected"\' : "" %>><%- text %></option>', null, {variable: null}),
  1145. setOptionValues: function (optionValues) {
  1146. this.optionValues = optionValues;
  1147. this.optionValues = _.result(this, "optionValues");
  1148. },
  1149. setMultiple: function (multiple) {
  1150. this.multiple = multiple;
  1151. this.$el.prop("multiple", multiple);
  1152. },
  1153. _renderOptions: function (nvps, selectedValues) {
  1154. var options = '';
  1155. for (var i = 0; i < nvps.length; i++) {
  1156. options = options + this.template({
  1157. text: nvps[i][0],
  1158. value: nvps[i][1],
  1159. selected: _.indexOf(selectedValues, nvps[i][1]) > -1
  1160. });
  1161. }
  1162. return options;
  1163. },
  1164. /**
  1165. Renders the options if `optionValues` is a list of name-value pairs. The
  1166. options are contained inside option groups if `optionValues` is a list of
  1167. object hashes. The name is rendered at the option text and the value is the
  1168. option value. If `optionValues` is a function, it is called without a
  1169. parameter.
  1170. */
  1171. render: function () {
  1172. this.$el.empty();
  1173. var optionValues = _.result(this, "optionValues");
  1174. var model = this.model;
  1175. var selectedValues = this.formatter.fromRaw(model.get(this.column.get("name")), model);
  1176. if (!_.isArray(optionValues)) throw new TypeError("optionValues must be an array");
  1177. var optionValue = null;
  1178. var optionText = null;
  1179. var optionValue = null;
  1180. var optgroupName = null;
  1181. var optgroup = null;
  1182. for (var i = 0; i < optionValues.length; i++) {
  1183. var optionValue = optionValues[i];
  1184. if (_.isArray(optionValue)) {
  1185. optionText = optionValue[0];
  1186. optionValue = optionValue[1];
  1187. this.$el.append(this.template({
  1188. text: optionText,
  1189. value: optionValue,
  1190. selected: _.indexOf(selectedValues, optionValue) > -1
  1191. }));
  1192. }
  1193. else if (_.isObject(optionValue)) {
  1194. optgroupName = optionValue.name;
  1195. optgroup = $("<optgroup></optgroup>", { label: optgroupName });
  1196. optgroup.append(this._renderOptions.call(this, optionValue.values, selectedValues));
  1197. this.$el.append(optgroup);
  1198. }
  1199. else {
  1200. throw new TypeError("optionValues elements must be a name-value pair or an object hash of { name: 'optgroup label', value: [option name-value pairs] }");
  1201. }
  1202. }
  1203. this.delegateEvents();
  1204. return this;
  1205. },
  1206. /**
  1207. Saves the value of the selected option to the model attribute.
  1208. */
  1209. save: function (e) {
  1210. var model = this.model;
  1211. var column = this.column;
  1212. model.set(column.get("name"), this.formatter.toRaw(this.$el.val(), model));
  1213. },
  1214. /**
  1215. Triggers a `backgrid:edited` event from the model so the body can close
  1216. this editor.
  1217. */
  1218. close: function (e) {
  1219. var model = this.model;
  1220. var column = this.column;
  1221. var command = new Command(e);
  1222. if (command.cancel()) {
  1223. e.stopPropagation();
  1224. model.trigger("backgrid:edited", model, column, new Command(e));
  1225. }
  1226. else if (command.save() || command.moveLeft() || command.moveRight() ||
  1227. command.moveUp() || command.moveDown() || e.type == "blur") {
  1228. e.preventDefault();
  1229. e.stopPropagation();
  1230. this.save(e);
  1231. model.trigger("backgrid:edited", model, column, new Command(e));
  1232. }
  1233. }
  1234. });
  1235. /**
  1236. SelectCell is also a different kind of cell in that upon going into edit mode
  1237. the cell renders a list of options to pick from, as opposed to an input box.
  1238. SelectCell cannot be referenced by its string name when used in a column
  1239. definition because it requires an `optionValues` class attribute to be
  1240. defined. `optionValues` can either be a list of name-value pairs, to be
  1241. rendered as options, or a list of object hashes which consist of a key *name*
  1242. which is the option group name, and a key *values* which is a list of
  1243. name-value pairs to be rendered as options under that option group.
  1244. In addition, `optionValues` can also be a parameter-less function that
  1245. returns one of the above. If the options are static, it is recommended the
  1246. returned values to be memoized. `_.memoize()` is a good function to help with
  1247. that.
  1248. During display mode, the default formatter will normalize the raw model value
  1249. to an array of values whether the raw model value is a scalar or an
  1250. array. Each value is compared with the `optionValues` values using
  1251. Ecmascript's implicit type conversion rules. When exiting edit mode, no type
  1252. conversion is performed when saving into the model. This behavior is not
  1253. always desirable when the value type is anything other than string. To
  1254. control type conversion on the client-side, you should subclass SelectCell to
  1255. provide a custom formatter or provide the formatter to your column
  1256. definition.
  1257. See:
  1258. [$.fn.val()](http://api.jquery.com/val/)
  1259. @class Backgrid.SelectCell
  1260. @extends Backgrid.Cell
  1261. */
  1262. var SelectCell = Backgrid.SelectCell = Cell.extend({
  1263. /** @property */
  1264. className: "select-cell",
  1265. /** @property */
  1266. editor: SelectCellEditor,
  1267. /** @property */
  1268. multiple: false,
  1269. /** @property */
  1270. formatter: SelectFormatter,
  1271. /**
  1272. @property {Array.<Array>|Array.<{name: string, values: Array.<Array>}>} optionValues
  1273. */
  1274. optionValues: undefined,
  1275. /** @property */
  1276. delimiter: ', ',
  1277. /**
  1278. Initializer.
  1279. @param {Object} options
  1280. @param {Backbone.Model} options.model
  1281. @param {Backgrid.Column} options.column
  1282. @throws {TypeError} If `optionsValues` is undefined.
  1283. */
  1284. initialize: function (options) {
  1285. SelectCell.__super__.initialize.apply(this, arguments);
  1286. this.listenTo(this.model, "backgrid:edit", function (model, column, cell, editor) {
  1287. if (column.get("name") == this.column.get("name")) {
  1288. editor.setOptionValues(this.optionValues);
  1289. editor.setMultiple(this.multiple);
  1290. }
  1291. });
  1292. },
  1293. /**
  1294. Renders the label using the raw value as key to look up from `optionValues`.
  1295. @throws {TypeError} If `optionValues` is malformed.
  1296. */
  1297. render: function () {
  1298. this.$el.empty();
  1299. var optionValues = _.result(this, "optionValues");
  1300. var model = this.model;
  1301. var rawData = this.formatter.fromRaw(model.get(this.column.get("name")), model);
  1302. var selectedText = [];
  1303. try {
  1304. if (!_.isArray(optionValues) || _.isEmpty(optionValues)) throw new TypeError;
  1305. for (var k = 0; k < rawData.length; k++) {
  1306. var rawDatum = rawData[k];
  1307. for (var i = 0; i < optionValues.length; i++) {
  1308. var optionValue = optionValues[i];
  1309. if (_.isArray(optionValue)) {
  1310. var optionText = optionValue[0];
  1311. var optionValue = optionValue[1];
  1312. if (optionValue == rawDatum) selectedText.push(optionText);
  1313. }
  1314. else if (_.isObject(optionValue)) {
  1315. var optionGroupValues = optionValue.values;
  1316. for (var j = 0; j < optionGroupValues.length; j++) {
  1317. var optionGroupValue = optionGroupValues[j];
  1318. if (optionGroupValue[1] == rawDatum) {
  1319. selectedText.push(optionGroupValue[0]);
  1320. }
  1321. }
  1322. }
  1323. else {
  1324. throw new TypeError;
  1325. }
  1326. }
  1327. }
  1328. this.$el.append(selectedText.join(this.delimiter));
  1329. }
  1330. catch (ex) {
  1331. if (ex instanceof TypeError) {
  1332. throw new TypeError("'optionValues' must be of type {Array.<Array>|Array.<{name: string, values: Array.<Array>}>}");
  1333. }
  1334. throw ex;
  1335. }
  1336. this.delegateEvents();
  1337. return this;
  1338. }
  1339. });
  1340. /*
  1341. backgrid
  1342. http://github.com/wyuenho/backgrid
  1343. Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors
  1344. Licensed under the MIT license.
  1345. */
  1346. /**
  1347. A Column is a placeholder for column metadata.
  1348. You usually don't need to create an instance of this class yourself as a
  1349. collection of column instances will be created for you from a list of column
  1350. attributes in the Backgrid.js view class constructors.
  1351. @class Backgrid.Column
  1352. @extends Backbone.Model
  1353. */
  1354. var Column = Backgrid.Column = Backbone.Model.extend({
  1355. /**
  1356. @cfg {Object} defaults Column defaults. To override any of these default
  1357. values, you can either change the prototype directly to override
  1358. Column.defaults globally or extend Column and supply the custom class to
  1359. Backgrid.Grid:
  1360. // Override Column defaults globally
  1361. Column.prototype.defaults.sortable = false;
  1362. // Override Column defaults locally
  1363. var MyColumn = Column.extend({
  1364. defaults: _.defaults({
  1365. editable: false
  1366. }, Column.prototype.defaults)
  1367. });
  1368. var grid = new Backgrid.Grid(columns: new Columns([{...}, {...}], {
  1369. model: MyColumn
  1370. }));
  1371. @cfg {string} [defaults.name] The default name of the model attribute.
  1372. @cfg {string} [defaults.label] The default label to show in the header.
  1373. @cfg {string|Backgrid.Cell} [defaults.cell] The default cell type. If this
  1374. is a string, the capitalized form will be used to look up a cell class in
  1375. Backbone, i.e.: string => StringCell. If a Cell subclass is supplied, it is
  1376. initialized with a hash of parameters. If a Cell instance is supplied, it
  1377. is used directly.
  1378. @cf…

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