-
Notifications
You must be signed in to change notification settings - Fork 3
/
backgrid.js
2599 lines (2099 loc) · 73.1 KB
/
backgrid.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function (root, $$, _, Backbone) {
"use strict";
/*
backgrid
http://github.com/wyuenho/backgrid
Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors
Licensed under the MIT @license.
*/
var window = root;
// Copyright 2009, 2010 Kristopher Michael Kowal
// https://github.com/kriskowal/es5-shim
// ES5 15.5.4.20
// http://es5.github.com/#x15.5.4.20
var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" +
"\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" +
"\u2029\uFEFF";
if (!String.prototype.trim || ws.trim()) {
// http://blog.stevenlevithan.com/archives/faster-trim-javascript
// http://perfectionkills.com/whitespace-deviations/
ws = "[" + ws + "]";
var trimBeginRegexp = new RegExp("^" + ws + ws + "*"),
trimEndRegexp = new RegExp(ws + ws + "*$");
String.prototype.trim = function trim() {
if (this === undefined || this === null) {
throw new TypeError("can't convert " + this + " to object");
}
return String(this)
.replace(trimBeginRegexp, "")
.replace(trimEndRegexp, "");
};
}
function lpad(str, length, padstr) {
var paddingLen = length - (str + '').length;
paddingLen = paddingLen < 0 ? 0 : paddingLen;
var padding = '';
for (var i = 0; i < paddingLen; i++) {
padding = padding + padstr;
}
return padding + str;
}
var Backgrid = root.Backgrid = {
VERSION: "0.2.6",
Extension: {},
requireOptions: function (options, requireOptionKeys) {
for (var i = 0; i < requireOptionKeys.length; i++) {
var key = requireOptionKeys[i];
if (_.isUndefined(options[key])) {
throw new TypeError("'" + key + "' is required");
}
}
},
resolveNameToClass: function (name, suffix) {
if (_.isString(name)) {
var key = _.map(name.split('-'), function (e) {
return e.slice(0, 1).toUpperCase() + e.slice(1);
}).join('') + suffix;
var klass = Backgrid[key] || Backgrid.Extension[key];
if (_.isUndefined(klass)) {
throw new ReferenceError("Class '" + key + "' not found");
}
return klass;
}
return name;
},
callByNeed: function () {
var value = arguments[0];
if (!_.isFunction(value)) return value;
var context = arguments[1];
var args = [].slice.call(arguments, 2);
return value.apply(context, !!(args + '') ? args : void 0);
}
};
_.extend(Backgrid, Backbone.Events);
/**
Command translates a DOM Event into commands that Backgrid
recognizes. Interested parties can listen on selected Backgrid events that
come with an instance of this class and act on the commands.
It is also possible to globally rebind the keyboard shortcuts by replacing
the methods in this class' prototype.
@class Backgrid.Command
@constructor
*/
var Command = Backgrid.Command = function (evt) {
_.extend(this, {
altKey: !!evt.altKey,
"char": evt["char"],
charCode: evt.charCode,
ctrlKey: !!evt.ctrlKey,
key: evt.key,
keyCode: evt.keyCode,
locale: evt.locale,
location: evt.location,
metaKey: !!evt.metaKey,
repeat: !!evt.repeat,
shiftKey: !!evt.shiftKey,
which: evt.which
});
};
_.extend(Command.prototype, {
/**
Up Arrow
@member Backgrid.Command
*/
moveUp: function () { return this.keyCode == 38; },
/**
Down Arrow
@member Backgrid.Command
*/
moveDown: function () { return this.keyCode === 40; },
/**
Shift Tab
@member Backgrid.Command
*/
moveLeft: function () { return this.shiftKey && this.keyCode === 9; },
/**
Tab
@member Backgrid.Command
*/
moveRight: function () { return !this.shiftKey && this.keyCode === 9; },
/**
Enter
@member Backgrid.Command
*/
save: function () { return this.keyCode === 13; },
/**
Esc
@member Backgrid.Command
*/
cancel: function () { return this.keyCode === 27; },
/**
None of the above.
@member Backgrid.Command
*/
passThru: function () {
return !(this.moveUp() || this.moveDown() || this.moveLeft() ||
this.moveRight() || this.save() || this.cancel());
}
});
/*
backgrid
http://github.com/wyuenho/backgrid
Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors
Licensed under the MIT @license.
*/
/**
Just a convenient class for interested parties to subclass.
The default Cell classes don't require the formatter to be a subclass of
Formatter as long as the fromRaw(rawData) and toRaw(formattedData) methods
are defined.
@abstract
@class Backgrid.CellFormatter
@constructor
*/
var CellFormatter = Backgrid.CellFormatter = function () {};
_.extend(CellFormatter.prototype, {
/**
Takes a raw value from a model and returns an optionally formatted string
for display. The default implementation simply returns the supplied value
as is without any type conversion.
@member Backgrid.CellFormatter
@param {*} rawData
@return {*}
*/
fromRaw: function (rawData) {
return rawData;
},
/**
Takes a formatted string, usually from user input, and returns a
appropriately typed value for persistence in the model.
If the user input is invalid or unable to be converted to a raw value
suitable for persistence in the model, toRaw must return `undefined`.
@member Backgrid.CellFormatter
@param {string} formattedData
@return {*|undefined}
*/
toRaw: function (formattedData) {
return formattedData;
}
});
/**
A floating point number formatter. Doesn't understand notation at the moment.
@class Backgrid.NumberFormatter
@extends Backgrid.CellFormatter
@constructor
@throws {RangeError} If decimals < 0 or > 20.
*/
var NumberFormatter = Backgrid.NumberFormatter = function (options) {
options = options ? _.clone(options) : {};
_.extend(this, this.defaults, options);
if (this.decimals < 0 || this.decimals > 20) {
throw new RangeError("decimals must be between 0 and 20");
}
};
NumberFormatter.prototype = new CellFormatter();
_.extend(NumberFormatter.prototype, {
/**
@member Backgrid.NumberFormatter
@cfg {Object} options
@cfg {number} [options.decimals=2] Number of decimals to display. Must be an integer.
@cfg {string} [options.decimalSeparator='.'] The separator to use when
displaying decimals.
@cfg {string} [options.orderSeparator=','] The separator to use to
separator thousands. May be an empty string.
*/
defaults: {
decimals: 2,
decimalSeparator: '.',
orderSeparator: ','
},
HUMANIZED_NUM_RE: /(\d)(?=(?:\d{3})+$)/g,
/**
Takes a floating point number and convert it to a formatted string where
every thousand is separated by `orderSeparator`, with a `decimal` number of
decimals separated by `decimalSeparator`. The number returned is rounded
the usual way.
@member Backgrid.NumberFormatter
@param {number} number
@return {string}
*/
fromRaw: function (number) {
if (_.isNull(number) || _.isUndefined(number)) return '';
number = number.toFixed(~~this.decimals);
var parts = number.split('.');
var integerPart = parts[0];
var decimalPart = parts[1] ? (this.decimalSeparator || '.') + parts[1] : '';
return integerPart.replace(this.HUMANIZED_NUM_RE, '$1' + this.orderSeparator) + decimalPart;
},
/**
Takes a string, possibly formatted with `orderSeparator` and/or
`decimalSeparator`, and convert it back to a number.
@member Backgrid.NumberFormatter
@param {string} formattedData
@return {number|undefined} Undefined if the string cannot be converted to
a number.
*/
toRaw: function (formattedData) {
var rawData = '';
var thousands = formattedData.trim().split(this.orderSeparator);
for (var i = 0; i < thousands.length; i++) {
rawData += thousands[i];
}
var decimalParts = rawData.split(this.decimalSeparator);
rawData = '';
for (var i = 0; i < decimalParts.length; i++) {
rawData = rawData + decimalParts[i] + '.';
}
if (rawData[rawData.length - 1] === '.') {
rawData = rawData.slice(0, rawData.length - 1);
}
var result = (rawData * 1).toFixed(~~this.decimals) * 1;
if (_.isNumber(result) && !_.isNaN(result)) return result;
}
});
/**
Formatter to converts between various datetime formats.
This class only understands ISO-8601 formatted datetime strings and UNIX
offset (number of milliseconds since UNIX Epoch). See
Backgrid.Extension.MomentFormatter if you need a much more flexible datetime
formatter.
@class Backgrid.DatetimeFormatter
@extends Backgrid.CellFormatter
@constructor
@throws {Error} If both `includeDate` and `includeTime` are false.
*/
var DatetimeFormatter = Backgrid.DatetimeFormatter = function (options) {
options = options ? _.clone(options) : {};
_.extend(this, this.defaults, options);
if (!this.includeDate && !this.includeTime) {
throw new Error("Either includeDate or includeTime must be true");
}
};
DatetimeFormatter.prototype = new CellFormatter();
_.extend(DatetimeFormatter.prototype, {
/**
@member Backgrid.DatetimeFormatter
@cfg {Object} options
@cfg {boolean} [options.includeDate=true] Whether the values include the
date part.
@cfg {boolean} [options.includeTime=true] Whether the values include the
time part.
@cfg {boolean} [options.includeMilli=false] If `includeTime` is true,
whether to include the millisecond part, if it exists.
*/
defaults: {
includeDate: true,
includeTime: true,
includeMilli: false
},
DATE_RE: /^([+\-]?\d{4})-(\d{2})-(\d{2})$/,
TIME_RE: /^(\d{2}):(\d{2}):(\d{2})(\.(\d{3}))?$/,
ISO_SPLITTER_RE: /T|Z| +/,
_convert: function (data, validate) {
var date, time = null;
if (_.isNumber(data)) {
var jsDate = new Date(data);
date = lpad(jsDate.getUTCFullYear(), 4, 0) + '-' + lpad(jsDate.getUTCMonth() + 1, 2, 0) + '-' + lpad(jsDate.getUTCDate(), 2, 0);
time = lpad(jsDate.getUTCHours(), 2, 0) + ':' + lpad(jsDate.getUTCMinutes(), 2, 0) + ':' + lpad(jsDate.getUTCSeconds(), 2, 0);
}
else {
data = data.trim();
var parts = data.split(this.ISO_SPLITTER_RE) || [];
date = this.DATE_RE.test(parts[0]) ? parts[0] : '';
time = date && parts[1] ? parts[1] : this.TIME_RE.test(parts[0]) ? parts[0] : '';
}
var YYYYMMDD = this.DATE_RE.exec(date) || [];
var HHmmssSSS = this.TIME_RE.exec(time) || [];
if (validate) {
if (this.includeDate && _.isUndefined(YYYYMMDD[0])) return;
if (this.includeTime && _.isUndefined(HHmmssSSS[0])) return;
if (!this.includeDate && date) return;
if (!this.includeTime && time) return;
}
var jsDate = new Date(Date.UTC(YYYYMMDD[1] * 1 || 0,
YYYYMMDD[2] * 1 - 1 || 0,
YYYYMMDD[3] * 1 || 0,
HHmmssSSS[1] * 1 || null,
HHmmssSSS[2] * 1 || null,
HHmmssSSS[3] * 1 || null,
HHmmssSSS[5] * 1 || null));
var result = '';
if (this.includeDate) {
result = lpad(jsDate.getUTCFullYear(), 4, 0) + '-' + lpad(jsDate.getUTCMonth() + 1, 2, 0) + '-' + lpad(jsDate.getUTCDate(), 2, 0);
}
if (this.includeTime) {
result = result + (this.includeDate ? 'T' : '') + lpad(jsDate.getUTCHours(), 2, 0) + ':' + lpad(jsDate.getUTCMinutes(), 2, 0) + ':' + lpad(jsDate.getUTCSeconds(), 2, 0);
if (this.includeMilli) {
result = result + '.' + lpad(jsDate.getUTCMilliseconds(), 3, 0);
}
}
if (this.includeDate && this.includeTime) {
result += "Z";
}
return result;
},
/**
Converts an ISO-8601 formatted datetime string to a datetime string, date
string or a time string. The timezone is ignored if supplied.
@member Backgrid.DatetimeFormatter
@param {string} rawData
@return {string|null|undefined} ISO-8601 string in UTC. Null and undefined
values are returned as is.
*/
fromRaw: function (rawData) {
if (_.isNull(rawData) || _.isUndefined(rawData)) return '';
return this._convert(rawData);
},
/**
Converts an ISO-8601 formatted datetime string to a datetime string, date
string or a time string. The timezone is ignored if supplied. This method
parses the input values exactly the same way as
Backgrid.Extension.MomentFormatter#fromRaw(), in addition to doing some
sanity checks.
@member Backgrid.DatetimeFormatter
@param {string} formattedData
@return {string|undefined} ISO-8601 string in UTC. Undefined if a date is
found when `includeDate` is false, or a time is found when `includeTime` is
false, or if `includeDate` is true and a date is not found, or if
`includeTime` is true and a time is not found.
*/
toRaw: function (formattedData) {
return this._convert(formattedData, true);
}
});
/**
Formatter to convert any value to string.
@class Backgrid.StringFormatter
@extends Backgrid.CellFormatter
@constructor
*/
var StringFormatter = Backgrid.StringFormatter = function () {};
StringFormatter.prototype = new CellFormatter();
_.extend(StringFormatter.prototype, {
/**
Converts any value to a string using Ecmascript's implicit type
conversion. If the given value is `null` or `undefined`, an empty string is
returned instead.
@member Backgrid.StringFormatter
@param {*} rawValue
@return {string}
*/
fromRaw: function (rawValue) {
if (_.isUndefined(rawValue) || _.isNull(rawValue)) return '';
return rawValue + '';
}
});
/**
Simple email validation formatter.
@class Backgrid.EmailFormatter
@extends Backgrid.CellFormatter
@constructor
*/
var EmailFormatter = Backgrid.EmailFormatter = function () {};
EmailFormatter.prototype = new CellFormatter();
_.extend(EmailFormatter.prototype, {
/**
Return the input if it is a string that contains an '@' character and if
the strings before and after '@' are non-empty. If the input does not
validate, `undefined` is returned.
@member Backgrid.EmailFormatter
@param {*} formattedData
@return {string|undefined}
*/
toRaw: function (formattedData) {
var parts = formattedData.trim().split("@");
if (parts.length === 2 && _.all(parts)) {
return formattedData;
}
}
});
/**
Formatter for SelectCell.
@class Backgrid.SelectFormatter
@extends Backgrid.CellFormatter
@constructor
*/
var SelectFormatter = Backgrid.SelectFormatter = function () {};
SelectFormatter.prototype = new CellFormatter();
_.extend(SelectFormatter.prototype, {
/**
Normalizes raw scalar or array values to an array.
@member Backgrid.SelectFormatter
@param {*} rawValue
@return {Array.<*>}
*/
fromRaw: function (rawValue) {
return _.isArray(rawValue) ? rawValue : rawValue != null ? [rawValue] : [];
}
});
/*
backgrid
http://github.com/wyuenho/backgrid
Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors
Licensed under the MIT @license.
*/
/**
Generic cell editor base class. Only defines an initializer for a number of
required parameters.
@abstract
@class Backgrid.CellEditor
@extends Backbone.View
*/
var CellEditor = Backgrid.CellEditor = Backbone.View.extend({
/**
Initializer.
@param {Object} options
@param {Backgrid.CellFormatter} options.formatter
@param {Backgrid.Column} options.column
@param {Backbone.Model} options.model
@throws {TypeError} If `formatter` is not a formatter instance, or when
`model` or `column` are undefined.
*/
initialize: function (options) {
Backgrid.requireOptions(options, ["formatter", "column", "model"]);
this.formatter = options.formatter;
this.column = options.column;
if (!(this.column instanceof Column)) {
this.column = new Column(this.column);
}
this.listenTo(this.model, "backgrid:editing", this.postRender);
},
/**
Post-rendering setup and initialization. Focuses the cell editor's `el` in
this default implementation. **Should** be called by Cell classes after
calling Backgrid.CellEditor#render.
*/
postRender: function (model, column) {
if (column == null || column.get("name") == this.column.get("name")) {
this.$el.focus();
}
return this;
}
});
/**
InputCellEditor the cell editor type used by most core cell types. This cell
editor renders a text input box as its editor. The input will render a
placeholder if the value is empty on supported browsers.
@class Backgrid.InputCellEditor
@extends Backgrid.CellEditor
*/
var InputCellEditor = Backgrid.InputCellEditor = CellEditor.extend({
/** @property */
tagName: "input",
/** @property */
attributes: {
type: "text"
},
/** @property */
events: {
"blur": "saveOrCancel",
"keydown": "saveOrCancel"
},
/**
Initializer. Removes this `el` from the DOM when a `done` event is
triggered.
@param {Object} options
@param {Backgrid.CellFormatter} options.formatter
@param {Backgrid.Column} options.column
@param {Backbone.Model} options.model
@param {string} [options.placeholder]
*/
initialize: function (options) {
CellEditor.prototype.initialize.apply(this, arguments);
if (options.placeholder) {
this.$el.attr("placeholder", options.placeholder);
}
},
/**
Renders a text input with the cell value formatted for display, if it
exists.
*/
render: function () {
this.$el.val(this.formatter.fromRaw(this.model.get(this.column.get("name"))));
return this;
},
/**
If the key pressed is `enter`, `tab`, `up`, or `down`, converts the value
in the editor to a raw value for saving into the model using the formatter.
If the key pressed is `esc` the changes are undone.
If the editor goes out of focus (`blur`) but the value is invalid, the
event is intercepted and cancelled so the cell remains in focus pending for
further action. The changes are saved otherwise.
Triggers a Backbone `backgrid:edited` event from the model when successful,
and `backgrid:error` if the value cannot be converted. Classes listening to
the `error` event, usually the Cell classes, should respond appropriately,
usually by rendering some kind of error feedback.
@param {Event} e
*/
saveOrCancel: function (e) {
var formatter = this.formatter;
var model = this.model;
var column = this.column;
var command = new Command(e);
var blurred = e.type === "blur";
if (command.moveUp() || command.moveDown() || command.moveLeft() || command.moveRight() ||
command.save() || blurred) {
e.preventDefault();
e.stopPropagation();
var val = this.$el.val();
var newValue = formatter.toRaw(val);
if (_.isUndefined(newValue)) {
model.trigger("backgrid:error", model, column, val);
}
else {
model.set(column.get("name"), newValue);
model.trigger("backgrid:edited", model, column, command);
}
}
// esc
else if (command.cancel()) {
// undo
e.stopPropagation();
model.trigger("backgrid:edited", model, column, command);
}
},
postRender: function (model, column) {
if (column == null || column.get("name") == this.column.get("name")) {
// move the cursor to the end on firefox if text is right aligned
if (this.$el.css("text-align") === "right") {
var val = this.$el.val();
this.$el.focus().val(null).val(val);
}
else this.$el.focus();
}
return this;
}
});
/**
The super-class for all Cell types. By default, this class renders a plain
table cell with the model value converted to a string using the
formatter. The table cell is clickable, upon which the cell will go into
editor mode, which is rendered by a Backgrid.InputCellEditor instance by
default. Upon encountering any formatting errors, this class will add an
`error` CSS class to the table cell.
@abstract
@class Backgrid.Cell
@extends Backbone.View
*/
var Cell = Backgrid.Cell = Backbone.View.extend({
/** @property */
tagName: "td",
/**
@property {Backgrid.CellFormatter|Object|string} [formatter=new CellFormatter()]
*/
formatter: new CellFormatter(),
/**
@property {Backgrid.CellEditor} [editor=Backgrid.InputCellEditor] The
default editor for all cell instances of this class. This value must be a
class, it will be automatically instantiated upon entering edit mode.
See Backgrid.CellEditor
*/
editor: InputCellEditor,
/** @property */
events: {
"click": "enterEditMode"
},
/**
Initializer.
@param {Object} options
@param {Backbone.Model} options.model
@param {Backgrid.Column} options.column
@throws {ReferenceError} If formatter is a string but a formatter class of
said name cannot be found in the Backgrid module.
*/
initialize: function (options) {
Backgrid.requireOptions(options, ["model", "column"]);
this.column = options.column;
if (!(this.column instanceof Column)) {
this.column = new Column(this.column);
}
var column = this.column, model = this.model, $el = this.$el;
this.formatter = Backgrid.resolveNameToClass(column.get("formatter") ||
this.formatter, "Formatter");
this.editor = Backgrid.resolveNameToClass(this.editor, "CellEditor");
this.listenTo(model, "change:" + column.get("name"), function () {
if (!$el.hasClass("editor")) this.render();
});
this.listenTo(model, "backgrid:error", this.renderError);
this.listenTo(column, "change:editable change:sortable change:renderable",
function (column) {
var changed = column.changedAttributes();
for (var key in changed) {
if (changed.hasOwnProperty(key)) {
$el.toggleClass(key, changed[key]);
}
}
});
if (column.get("editable")) $el.addClass("editable");
if (column.get("sortable")) $el.addClass("sortable");
if (column.get("renderable")) $el.addClass("renderable");
},
/**
Render a text string in a table cell. The text is converted from the
model's raw value for this cell's column.
*/
render: function () {
this.$el.empty();
this.$el.text(this.formatter.fromRaw(this.model.get(this.column.get("name"))));
this.delegateEvents();
return this;
},
/**
If this column is editable, a new CellEditor instance is instantiated with
its required parameters. An `editor` CSS class is added to the cell upon
entering edit mode.
This method triggers a Backbone `backgrid:edit` event from the model when
the cell is entering edit mode and an editor instance has been constructed,
but before it is rendered and inserted into the DOM. The cell and the
constructed cell editor instance are sent as event parameters when this
event is triggered.
When this cell has finished switching to edit mode, a Backbone
`backgrid:editing` event is triggered from the model. The cell and the
constructed cell instance are also sent as parameters in the event.
When the model triggers a `backgrid:error` event, it means the editor is
unable to convert the current user input to an apprpriate value for the
model's column, and an `error` CSS class is added to the cell accordingly.
*/
enterEditMode: function () {
var model = this.model;
var column = this.column;
var editable = Backgrid.callByNeed(column.get("editable"), column, model);
if (editable) {
this.currentEditor = new this.editor({
column: this.column,
model: this.model,
formatter: this.formatter
});
model.trigger("backgrid:edit", model, column, this, this.currentEditor);
// Need to redundantly undelegate events for Firefox
this.undelegateEvents();
this.$el.empty();
this.$el.append(this.currentEditor.$el);
this.currentEditor.render();
this.$el.addClass("editor");
model.trigger("backgrid:editing", model, column, this, this.currentEditor);
}
},
/**
Put an `error` CSS class on the table cell.
*/
renderError: function (model, column) {
if (column == null || column.get("name") == this.column.get("name")) {
this.$el.addClass("error");
}
},
/**
Removes the editor and re-render in display mode.
*/
exitEditMode: function () {
this.$el.removeClass("error");
this.currentEditor.remove();
this.stopListening(this.currentEditor);
delete this.currentEditor;
this.$el.removeClass("editor");
this.render();
},
/**
Clean up this cell.
@chainable
*/
remove: function () {
if (this.currentEditor) {
this.currentEditor.remove.apply(this.currentEditor, arguments);
delete this.currentEditor;
}
return Backbone.View.prototype.remove.apply(this, arguments);
}
});
/**
StringCell displays HTML escaped strings and accepts anything typed in.
@class Backgrid.StringCell
@extends Backgrid.Cell
*/
var StringCell = Backgrid.StringCell = Cell.extend({
/** @property */
className: "string-cell",
formatter: new StringFormatter()
});
/**
UriCell renders an HTML `<a>` anchor for the value and accepts URIs as user
input values. No type conversion or URL validation is done by the formatter
of this cell. Users who need URL validation are encourage to subclass UriCell
to take advantage of the parsing capabilities of the HTMLAnchorElement
available on HTML5-capable browsers or using a third-party library like
[URI.js](https://github.com/medialize/URI.js).
@class Backgrid.UriCell
@extends Backgrid.Cell
*/
var UriCell = Backgrid.UriCell = Cell.extend({
/** @property */
className: "uri-cell",
render: function () {
this.$el.empty();
var formattedValue = this.formatter.fromRaw(this.model.get(this.column.get("name")));
this.$el.append($("<a>", {
tabIndex: -1,
href: formattedValue,
title: formattedValue,
target: "_blank"
}).text(formattedValue));
this.delegateEvents();
return this;
}
});
/**
Like Backgrid.UriCell, EmailCell renders an HTML `<a>` anchor for the
value. The `href` in the anchor is prefixed with `mailto:`. EmailCell will
complain if the user enters a string that doesn't contain the `@` sign.
@class Backgrid.EmailCell
@extends Backgrid.StringCell
*/
var EmailCell = Backgrid.EmailCell = StringCell.extend({
/** @property */
className: "email-cell",
formatter: new EmailFormatter(),
render: function () {
this.$el.empty();
var formattedValue = this.formatter.fromRaw(this.model.get(this.column.get("name")));
this.$el.append($("<a>", {
tabIndex: -1,
href: "mailto:" + formattedValue,
title: formattedValue
}).text(formattedValue));
this.delegateEvents();
return this;
}
});
/**
NumberCell is a generic cell that renders all numbers. Numbers are formatted
using a Backgrid.NumberFormatter.
@class Backgrid.NumberCell
@extends Backgrid.Cell
*/
var NumberCell = Backgrid.NumberCell = Cell.extend({
/** @property */
className: "number-cell",
/**
@property {number} [decimals=2] Must be an integer.
*/
decimals: NumberFormatter.prototype.defaults.decimals,
/** @property {string} [decimalSeparator='.'] */
decimalSeparator: NumberFormatter.prototype.defaults.decimalSeparator,
/** @property {string} [orderSeparator=','] */
orderSeparator: NumberFormatter.prototype.defaults.orderSeparator,
/** @property {Backgrid.CellFormatter} [formatter=Backgrid.NumberFormatter] */
formatter: NumberFormatter,
/**
Initializes this cell and the number formatter.
@param {Object} options
@param {Backbone.Model} options.model
@param {Backgrid.Column} options.column
*/
initialize: function (options) {
Cell.prototype.initialize.apply(this, arguments);
this.formatter = new this.formatter({
decimals: this.decimals,
decimalSeparator: this.decimalSeparator,
orderSeparator: this.orderSeparator
});
}
});
/**
An IntegerCell is just a Backgrid.NumberCell with 0 decimals. If a floating
point number is supplied, the number is simply rounded the usual way when
displayed.
@class Backgrid.IntegerCell
@extends Backgrid.NumberCell
*/
var IntegerCell = Backgrid.IntegerCell = NumberCell.extend({
/** @property */
className: "integer-cell",
/**
@property {number} decimals Must be an integer.
*/
decimals: 0
});
/**