-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathgrid.js
1568 lines (1322 loc) · 44.4 KB
/
grid.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
// Open JS Grid Version 2
// Requires RootJS
var grids = [];
(function($) {
/* TODO
textarea type
per row editing
adding
multigrids
row-highlight
added columns should not take a function for value, should use the cellTypes array
*/
/*
So you guys know, RootJS is a thing I've been working on for a while, it makes writing OOP code super easy
Root.jQueryPlugin uses that to make any RootJS object a jquery plugin. What that means is that when you define
and object like I have below, You get the following functionality.
$(selector).plugin()
$(selector).plugin({object of options})
$(selector).plugin("method")
$(selector).plugin("method","param1","param2")
$(selector).plugin("property")
$(selector).plugin("property","value")
*/
window.Grid = Root.jQueryPlugin("grid",{
// default settable options
opts : {
title : "", // title attribute on this table
action : "", // action url on this table
nRowsShowing : 10, // number of rows to show on load
minAllowedColWidth : 50, // when auto sizing columns, they can't be less than this size
minWidthForDynamicCols : 20,// dynamic cols, like row number and checkboxes have a smaller min width
class : "", // classes on this table
showPager : true,
deleting : false,
deleteConfirm: true,
checkboxes : false,
rowNumbers : false,
editing : false,
width : "100%",
rowHeight : null, // this is null to start because if you dont use it, it doesn't loop through stylesheets
page : 1
},
// public properties
cols : "", // comma list of columns to get data for
columns : {},
pager : null,
toSave : [],
// cell types
// you can add your own here as well
cellTypes : {
"text": function(value, columnOpts, grid) {
if(grid.opts.editing) {
return {
cellClass: "editable input",
cellValue: "<input type='text' value='"+value+"'/>"
}
}
},
"date": function(value, columnOpts, grid) {
if(grid.opts.editing) {
return {
cellClass: "editable input",
cellValue: "<input class='datepicker' type='text' value='"+value+"'/>"
}
}
},
"checkbox": function(value, columnOpts, grid) {
if(grid.opts.editing) {
var checked = value == 1 ? "checked" : "";
return {
cellClass: "editable center",
cellValue: "<input type='checkbox' "+checked+" value='"+value+"'/>"
}
}
},
"image": function(value, columnOpts, grid) {
return {
cellClass: "center",
cellValue: "<img src='"+value+"'/>"
}
},
"money": function(value, columnOpts, grid) {
return {
cellClass: "",
cellValue: "$"+value
}
},
"select" : function(value, columnOpts, grid) {
var select = grid.selects[columnOpts.col],
options = "";
for(i in select) {
if(value == i) {
options += "<option selected value='"+i+"'>"+select[i]+"</option>";
} else {
options += "<option value='"+i+"'>"+select[i]+"</option>";
}
}
return {
cellClass: "editable input select",
cellValue: "<select>"+options+"</select>"
}
}
},
// internal properties
sbWidth : 0,
start : 0,
end : 0,
totalRows : 0,
aColumnHeight :0,
gridHeight : 0,
$columns : null,
$cols : null,
firstLoad : true,
_stopColumnDrag : false,
// *********************************************************************************
// *********************************************************************************
// ** PRIVATE METHODS
// *********************************************************************************
// *********************************************************************************
_construct : function() {
// NOTE: anything done in here will only ever be done when the grid is first created
var $table = $(this.el);
// wrap the table with a div called columns. Jquery wrap doesnt work
var $columns = $("<div class='columns'></div>");
// wrap the columns with a div called gridWrapper. Jquery wrap doesnt work
// this will be our main html element
var $wrapper = $("<div class='gridWrapper'><span class='gridLoading'>Loading</span></div>");
$wrapper.insertAfter($table)
.append($columns)
.width(this.opts.width);
// add classes from opts
if(this.opts.class) {
$wrapper.addClass(this.opts.class);
}
// its cheaper to alter the stylesheet via JS instead of each cell after load
if(this.opts.rowHeight) {
var ss = document.styleSheets;
for(var i=0;i<ss.length;i++) {
if(ss[i].title == "openJsGrid") {
for(var j=0;j<ss[i].rules.length;j++) {
var r = ss[i].rules[j];
if(r.selectorText == "div.gridWrapper .columns .cell") {
r.style.height = this.opts.rowHeight + "px";
}
// and this doesn't really need to be here could be in JS
// this probably should read the padding so it knows what to add
if(r.selectorText == "div.gridWrapper .columns .cell:nth-child(2)") {
r.style.marginTop = this.opts.rowHeight + 15 + "px";
}
}
}
}
}
// reset our elemeng to the new wrapper, and restore the instance on the DOM
this.el = $wrapper[0];
this.el.instance = this;
// lets add our grid resizer block
$wrapper.append("<div class='gridResizer'></div>");
var self = this,
$grid = $(this.el),
table = $table[0],
$ths = $table.find("th");
// so we can access all grids from the outside
window.grids.push(this);
// lets take the attributes from the table element and store them
this._attrsToProps(table,this.opts);
// take the columns you want and store them in a comma sep list (easy to send to ajax)
this.cols = $table.find("th").map(function() {return $(this).attr("col")}).get().join(",");
// define this object on THIS instance
this.columns = {};
// loop through THs and store properties in an object
for(var i=0;i<=$ths.length;i++) {
if($ths.eq(i).length) {
var $col = $ths.eq(i),
col = $col[0],
colName = col.getAttribute("col");
this.columns[colName] = {header : $col.text()};
this._attrsToProps(col,this.columns[colName]);
}
}
// we dont need no damn tables
$table.remove();
// store some stuff we need
this.sbWidth = this._calculateScrollbarWidth();
// add the touch class if we have a touch devince
!!('ontouchstart' in window) && $grid.addClass("touch");
// call the load when the object is built
this.load();
//////////// EVENTS
// save event
if(this.opts.editing) {
$grid._on("click",".gridSave:not(.disabled)", self.saveRow, self);
$grid.on("click",".gridSave.disabled", function(){ return false });
// as you type, keep the object up to date
$grid._on("keyup",".cell :input", self.markForSaving, self);
// datepicker choose (datepicker is optional)
$grid._on("change",".cell :input.datepicker", self.markForSaving, self);
// datepicker choose (datepicker is optional)
$grid._on("change",".cell select", self.markForSaving, self);
}
// add custom cell types if needed
if(this.opts.cellTypes) {
this.extend(this.cellTypes,this.opts.cellTypes);
}
// as you type, keep the object up to date
$grid._on("click",".cell", self._handleCellClick, self);
// checkbox saving
$grid._on("click",".cell :checkbox", self.markForSaving, self);
// as you type, keep the object up to date
$grid._on("click",".headerCell", self.sort, self);
// row hover
//$grid._on("mouseover",".cell[data-row]",self.rowHover,self);
//$grid._on("mouseout" ,".cell[data-row]",self.rowHoverOut,self);
// grid resizer
$grid._on("mousedown",".gridResizer", self._gridResize, self);
// col resizers
var rs = ".headerCell .resizer";
$grid._on("mousedown", rs, self._columnResize, self).on("click",rs, function(e) {
// stop the header cell from being clicked
e.stopPropagation();
});
// delete button
if(this.opts.deleting) {
$grid._on("click","button.gridDeleteRow", self.deleteRow, self);
}
},
/*******
I think this function is finally done. No matter what your table padding, border,
cell padding, cell border, whatever, scrollbars or not. The math should always make it perfect
honestly, many days went into this math, and i'm quite proud of it. The whole grid comes down to this
function, and it being fast. Trying to optimize this as much as possible
*******/
_equalize : function(amt) {
var $grid = $(this.el), // our grid
$columns = this.$columns, // single columns container
$cols = this.$cols, // collection of each column
nCols = $cols.length, // how many columns
totalNCols = nCols,
gridHeight = this.gridHeight, // height of the grid
sbWidth = this.sbWidth, // scrollbar width
minAllowedColWidth = this.opts.minAllowedColWidth, // minium allowed width for columns
needsScrollbar = this.aColumnHeight > gridHeight, // if 1 column height is > grid height, we need to account for scrollbar
sbWidth = needsScrollbar ? sbWidth : 0, // use sbwidth or 0 if we needed a scroll bar
columns = this.columns, // our columns object
colName, col, i, name, customWidth, colwidth; // extra vars
var originalWidth = $grid.width(); // current width of the grid
this.fullWidth = originalWidth - sbWidth; // adjust width to scrollbar so we know how much space to fill
var playWidth = this.fullWidth; // playWidth is how much space minus set widths do we have
// adjust number of columns and full width to reflect manually set widths
for(colName in columns) {
col = columns[colName];
if("width" in col) {
if(playWidth - parseInt(col.width) > minAllowedColWidth) {
// adjust width for custom width cells
playWidth -= parseInt(col.width);
// no longer count this cell
nCols--;
}
}
}
for(i=0, l = $cols.length; i<l; i++) {
col = $cols[i];
name = col.getAttribute("col");
// bool if we have a customWidth or not
customWidth = "width" in this.columns[name];
// test pct here
// if we have a custom width, use that, otherwise, figure it out based on fullWidth / nCols
colWidth = customWidth ? parseInt(columns[name].width) : playWidth / nCols;
// meh
if(i == l-1) colWidth -= 1;
// apply the width to that column
col.style.width = colWidth + "px";
}
},
// resize event for each column
_columnResize : function(e,el) {
var self = this,
$grid = $(self.el),
customWidth, minSpace, i, l, maxWidth, minWidth,
startX = e.clientX,
$cell = $(el).parent(),
cell = $cell[0],
colName = cell.getAttribute("col"),
colOpts = this.columns[colName];
// prevent selections
$grid.addClass("resizing");
// store this so we dont have to access the dom anymore
colOpts.width = $cell.width();
// figure out the max this column can go
$cols = this.$cols;
minSpace = 0;
for(i=0, l = $cols.length; i<l; i++) {
col = $cols[i];
name = col.getAttribute("col");
// ingore the column were about to resize
if(name != colName) {
customWidth = "width" in this.columns[name];
// continue adding up the space the other columns take up
minSpace += customWidth ? parseInt(this.columns[name].width) : parseInt(this.opts.minAllowedColWidth);
}
}
// determine min and max width for this column
maxWidth = this.fullWidth - minSpace;
minWidth = ("dynamic" in colOpts) ? this.opts.minWidthForDynamicCols : this.opts.minAllowedColWidth;
// COLUMN RESIZING
$(document).bind("mouseup.grid",function() {
$(document).unbind("mousemove.grid");
$grid.removeClass("resizing");
self._equalize();
});
$cols = this.$cols, l = this.$cols.length;
$(document).bind("mousemove.grid",function(e) {
// width to be
var amt = (e.clientX - startX);
// make sure we're within our rights
if(colOpts.width + amt < maxWidth && colOpts.width + amt > minWidth) {
// change the width
colOpts.width += amt;
// adjust the header cell width so it can affect the others
startX = e.clientX;
// adjust the rest, except the header cell
self._equalize();
}
});
},
// resize method for the entire grid
_gridResize: function(e,el) {
// starting pos
var self = this,
startX = e.clientX;
$grid = $(self.el);
// turn off selection while resizing
$grid.addClass("resizing");
$(document).bind("mouseup.grid",function() {
$(document).unbind("mousemove.grid");
$grid.removeClass("resizing");
self._equalize();
});
$(document).bind("mousemove.grid",function(e) {
$grid.width( $grid.width() + (e.clientX - startX) );
// adjust the header cell width so it can affect the others
startX = e.clientX;
// if the width is tiny, add the small class
if($grid.width() < 600) {
$grid.addClass("small");
self.pager.slider.update();
} else if($grid.hasClass("small")) {
$grid.removeClass("small");
self.pager.slider.update();
}
// adjust the rest, except the header cell
self._equalize();
});
},
// often will be the case that browsers have different scrollbars
// this trick calculates that size
_calculateScrollbarWidth : function() {
var div = $('<div><div style="height:100px;"></div></div>').css({
width:50,
height:50,
overflow:"hidden",
position:"absolute",
top:-200,
left:-200
});
$('body').append(div);
var w1 = $('div', div).innerWidth();
div.css('overflow-y', 'auto');
var w2 = $('div', div).innerWidth();
$(div).remove();
var scrollbarWidth = (w1 - w2);
return scrollbarWidth;
},
_attrsToProps : function(el,obj) {
// takes all the attributes on some dom element and stores them
// as properties onto some other object
// im making this a method, cuz we will need to do this again for THs
var attrs = el.attributes;
for(var i=0, l=attrs.length; i<l; i++ ) {
obj[attrs[i].name] = attrs[i].value;
}
return obj;
},
// after load is done, we do these things
_afterLoad : function() {
var self = this,
$grid = $(this.el);
// call to create the pager
if(!this.pager) {
this.pager = Pager.inherit({grid : this});
} else {
this.pager.update();
}
/////////////////////////
// ADD CHECKBOX COLUMN
////////////////////////
if(this.opts.checkboxes) {
// add the column with a width
var $checkboxCol = this.addColumn("Checks", {
width: 35,
insertAt: 0,
header : " ",
cellClass : "center"
}, function(i) {
return "<input class='rowCheck' type='checkbox'/>";
})
}
/////////////////////////
// ADD ROW NUMBER COLUMN
////////////////////////
if(this.opts.rowNumbers && !Array.isArray(this.rows)) {
// add the column with a width
var $newCol = this.addColumn("rowNumbers", {
width: 35,
insertAt: 0,
header : " ",
cellClass : "center"
}, function(i) {
return i + self.start;
})
}
/////////////////////////
// ADD DATEPICKER STUFF
////////////////////////
if($.datepicker && $(".datepicker").length) {
$(".datepicker").datepicker({dateFormat: "yy-mm-dd"});
}
/////////////////////////
// ADD DELETE BUTTON COLUMN
////////////////////////
if(this.opts.deleting && !Array.isArray(this.rows)) {
// add the column with a width
var $deleteCol = this.addColumn("Delete", {width: 65, cellClass : "center"}, function() {
return self._render("deleteButton")();
})
}
/////////////////////////
// ADD SORTABLE BAR THING
////////////////////////
var $sortBar = $(this.el).find(".headerCell[col='"+this.opts.orderBy+"']").find(".sortbar").show();
if(this.opts.sort == "desc") $sortBar.addClass("desc");
/////////////////////////
// SET THE BLANK CELL HEIGHT TO MATCH
////////////////////////
var headerHeight = $grid.find(".headerCell:first").height();
$grid.find(".blankCell").css({
height: headerHeight
});
// what happens after ajax, stays after ajax.
this._cacheSize();
this._equalize();
// were done loading, close the notification
self.loadingDialog.close();
if($grid.width() < 600) {
$grid.addClass("small");
self.pager.slider.update();
} else if($grid.hasClass("small")) {
$grid.removeClass("small");
self.pager.slider.update();
}
// mark first load
this.firstLoad = false;
},
// stores up the current size and variables for equalize
// only call this to recache
// dont call this if the grid is gonna reload, itll get called anyway
_cacheSize : function() {
var $grid = $(this.el);
this.$columns = $grid.children(".columns");
this.$cols = this.$columns.children(".col");
this.aColumnHeight = this.$columns.children(".col:first").height();
this.gridHeight = $grid.height();
},
// because there is no true concept of a row,
// we need to run this call both rowClick and cellClick
_handleCellClick : function(e,el) {
var id = el.getAttribute("data-row"),
rowData= this.rows["_"+id];
// row check
if($(e.target).hasClass("rowCheck")) {
$(this.el).trigger("rowCheck", [$(e.target),rowData]);
}
// trigger cell click
$(this.el).trigger("cellClick", [$(el),rowData]);
// trigger row click
$rows = this.getRow(id);
// this isn't sending the array?
$(this.el).trigger("rowClick", [$rows,rowData]);
},
// template render
_render : function (template) {
var self = this;
return function (data) {
// Caches the template so that it may be manipulated.
// allows {!{ syntax for use with other template engines
var temple, regex = /{!?{([\w\.]+)}}/g;
// use template as string if its not defined
if(typeof self._templates[template] == "undefined") {
temple = template;
// use pre defined template
} else {
temple = self._templates[template];
}
// template replacement
temple = temple.replace(regex, function(match, $1) { return data[$1] });
// Get rid of any remaining, unused variables before returning.
return temple.replace(regex, '');
};
},
// html templates
_templates : {
deleteButton : "<button class='gridDeleteRow btn btn-mini'>X</button>",
cell : "<div class='cell {{cl}} grid-row-{{id}}' data-row='{{id}}' data-col='{{col}}'>{{val}}</div>",
columnHeader : ""+
"<div class='cell headerCell' col='{{col}}'>\
<span>{{header}}</span>\
<div class='resizer'></div>\
<div class='sortbar'>▾</div>\
</div>\
<!--<div class='cell blankCell' col='{{col}}'>Blank</div>-->\
",
confirm : ""+
"<div class='dialog gridConfirm'>\
<span>{{msg}}</span>\
<div class='buttons'>\
<button class='btn confirmOk'>OK</button>\
<button class='btn cancel'>Cancel</button>\
</div>\
</div>\
",
alert : ""+
"<div class='dialog gridAlert {{type}}'>\
<span class='label label-{{type}}'>{{title}}</span>\
<span class='body'>{{msg}}</span>\
<div class='buttons'>\
<button class='btn cancel'>OK</button>\
</div>\
</div>\
",
notify : ""+
"<div class='dialog gridNotify'>\
<span class='body'>{{msg}}</span>\
</div>\
",
pager : ""+
"<div class='pagination left'>\
<ul>\
<li class='disabled'>\
<a href='#' class='pager_showing'>showing \
<span class='pager_lower_limit'>{{start}}</span> - \
<span class='pager_upper_limit'>{{end}}</span>\
</a></li>\
<li class='gridPrev'><a href='#'>Prev</a></li>\
<li class='gridNext'><a href='#'>Next</a></li>\
<li class='slider'><span class='sliderSpan'>\
<div class='slider'>\
<div class='sliderTrack'></div>\
<div class='sliderThumb'></div>\
</div>\
</span>\
<li class='currentPage'><input type='text' value='{{page}}'/></li>\
<li class='search icon'><input type='text' value='{{search}}'/></li>\
</ul>\
</div>\
<div class='right'>\
<a class='disabled gridSave btn btn-primary' href='#'>Save</a>\
</div>\
"
},
// *********************************************************************************
// *********************************************************************************
// ** PUBLIC METHODS
// *********************************************************************************
// *********************************************************************************
// IDEA - ONLY EVER KEEP 30 ROWS ON THE DOM, REMOVE TOP AND BOTTOM ROWS AND STORE IN MEMORY
// ONLY CREATE 30 ROWS AT A TIME, NEVER MORE. FILTERING IS ALREADY DONE ON MEMORY, BUT WOULD NEED
// TO ADD BACK ROWS THAT ARE IN MEMORY AND NOT IN THE DOM, SHOULD BE EASY.
// public methods
load : function(opts) {
var self = this, packet, promise, rowHtml = "", colHtml = "",
col = 0, key = 0, pKey, rowCol = 0, cellValue, checked = 0,
cellClass = "", type;
// if we are reloading with options pass them in
// if(opts) this.grid(opts);
if(opts) this.opts = this.extend(this.opts,opts);
// register loadStart callback
$(this.el).trigger("loadStart");
// we have some more data than in this.opts that we wanna send to ajax
packet = $.extend({
cols : this.cols
},this.opts);
// cache the el because self.el changes some where?
var el = self.el
var cellTypes = self.cellTypes;
// show loading box
this.loadingDialog = this.notify("Loading");
/////////////////////////
// LOAD SELECT BOXES
////////////////////////
var selCol, colName, selectCols = [], selectPromise = $.Deferred();
for(colName in this.columns) {
selCol = this.columns[colName];
if(typeof selCol.type != "undefined" && selCol.type == "select") {
selectCols.push(colName);
}
}
// get all the drop downs, store the promise in case we wanna check this
if(selectCols.length && !self.selects) {
selectPromise = $.post(this.opts.action,{select : true, cols : selectCols},function(data) {
// by saving the data, we dont ever have to do this ajax call again til page reload
self.selects = data;
return true;
});
} else {
selectPromise.resolve();
}
promise = $.post(this.opts.action,packet,function(data) {
self.el = el; // fixes some problem i dont know :(
self.cellTypes = cellTypes;
var $grid = $(self.el),
$columns = $grid.find(".columns");
// store some data we got back
self.totalRows = data.nRows;
self.start = data.start;
self.end = Math.min(data.end,data.nRows);
self.saveable = data.saveable;
self.opts.orderBy = data.order_by;
self.opts.sort = data.sort;
// were gonna build the table in a string, then append it
// this is 1000000x times faster than dom manipulation
self.rows = data.rows;
// when our ajax is done, move on.
selectPromise.done(function() {
// it will be an object if it has data
if(!Array.isArray(data.rows)) {
// build the table in column form, instead of row form
for(col in self.columns) {
// options on the column
colOpts = self.columns[col];
// opening col div
colHtml += "<div class='col _"+(colOpts.type || '')+"' col='"+col+"'>";
// blank cells mess things up
if(colOpts.header == "") colOpts.header = " "
// add header cell with resizer, sortable bar and blank cell
// this is only the header and not the whole column because we want the ability
// to keep adding strings to the return for speed
colHtml += self._render("columnHeader")(colOpts);
for(key in data.rows) {
pkey = key.substr(1);
row = data.rows[key];
for(rowCol in row) {
if(rowCol === col) {
// main value
cellValue = row[col],
cellClass = "";
// setup some types
if(typeof self.cellTypes[colOpts.type] == "function") {
typeOpts = self.cellTypes[colOpts.type](cellValue,colOpts,self);
// protect a no return
if(typeof typeOpts == "undefined") typeOpts = {cellValue : cellValue,cellClass: ""};
cellValue = typeOpts.cellValue;
cellClass = typeOpts.cellClass;
}
// empty cells kinda mess with things
if(cellValue == "") cellValue = " ";
// add linking
// this is not a type because you can link anything by adding href
if(colOpts.href) {
// make some tokens for use in the href
var linkTokens = {value : cellValue}
// add all the column values, column.Title i.e.
for(var aCol in row) linkTokens["columns."+aCol] = row[aCol];
// render the href with the tokens
var href = self._render(colOpts.href)(linkTokens);
// wrap the cell value in an a tag with the rendered href
cellValue = "<a href='"+href+"'>"+cellValue+"</a>";
}
// create the cell from template
colHtml += self._render("cell")({
cl : cellClass,
id : pkey,
col : col,
val : cellValue
});
}
}
}
colHtml += "</div>";
}
} else {
colHtml = "No Rows";
}
// hide our loading
$grid.find(".gridLoading").hide();
// place all the content
$columns.html(colHtml);
// do things after ajax
self._afterLoad();
// register loadComplate Callback
$(self.el).trigger("loadComplete",self);
});
},"json");
return promise;
},
// [none | success | warning | important | info | inverse]
// helper dialog alert function
alert : function(type, title, msg) {
return Dialog.inherit({
tmpl : "alert",
type: type,
title: title,
msg : msg,
grid: this
}).show();
},
// helper dialog notify method
notify : function(msg, ms) {
var self = this;
// our opts
var opts = {msg:msg, grid:this};
// if we wanted a timer
if(ms) opts.autoFadeTimer = ms;
// create and show
return Dialog.inherit(opts).show();
},
// shortcut error function
error : function(msg) {
return this.alert("important", "Error!", msg);
},
// a confrim dialog box
confirm : function(msg, callback) {
var $grid = $(this.el);
var dialog = Dialog.inherit({
tmpl : "confirm",
msg : msg,
grid : this
}).show();
// add our confirm ok
dialog.$dialog.one("click",".confirmOk",callback);
return dialog;
},
// debouncing the typing
_filter : function(e,el) {
var self = this,
$el = $(el);
// store on pager
this.pager.query = $el.val();
// start typing timer
clearTimeout(this.debounce);
this.debounce = setTimeout(function() {
self.filter( $el.val() )
},150);
},
// finds matches in the dom as fast as i know how
// do intelligent searches with column:
// right click a column header and choose "search on" which would fill out the search filter
filter : function(val) {
var $grid = $(this.el),
$all = $grid.find("[data-row]"),
$cols = $grid.find(".col");
if(val) {
var matches = [],
val = val.toLowerCase();
for(id in this.rows) {
var row = this.rows[id],
id = id.substring(1);
for(key in row) {
var string = row[key].toLowerCase();
if(~string.indexOf(val) && !~matches.indexOf(id)) matches.push(id);
}
}
$all.hide();
$all.removeClass("topMargin");
if(matches.length) {
$(".cell.temp").remove();
for(i=0;i<matches.length;i++) {
// test with jsperf
$grid.find(".grid-row-"+matches[i]).show();
}
// because the css for nth-child(2) isn't math accurate anymore with hidden rows
// we need to find the nth-child(2) ourselves for search results. But we keep the css when all are showing
// since thats the most used case
$cols.find(".cell:visible:eq(1)").addClass("topMargin");
} else {
$cols.append("<div class='cell temp'> </div>");
}
} else {
$all.show();
$all.removeClass("topMargin");
}
// we need to recache the scroll height account for scrollbars
//this.scrollHeight = $grid.find(".columns")[0].scrollHeight;
this.aColumnHeight = $grid.children(".columns").children(".col:first").height();
this._equalize();
},
// adds a column with options to the grid
// runs a function on the value so you can pass in as it builds
// opts : {width, insertAt, cellClass}
addColumn : function(col, opts, fn) {
// if it already exists delete it
if(this.colExists(col)) {
$(this.el).find(".col[col='"+col+"']").remove();
}
// create the new column from template
var newCol = "<div class='col dynamic' col='"+col+"'>",
$newCol,pkey;
// column header stuff
var header = opts.header || col;
newCol += this._render("columnHeader")({col : col, header : header});
// if the value fn wasn't passed, use blank
if(typeof fn != "function") fn = function(i) { return " " }
// add in rows;
var i = 0;
for(key in this.rows) {
pkey = key.substr(1);
newCol += this._render("cell")({
cl : opts.cellClass || "",
id : pkey,
col : col,
val : fn(i, this.rows[key])
});
i++;
}
// cap off our col
newCol += "</div>";
// DOMit
$newCol = $(newCol);
// add to the DOM
this._insertCol($newCol,opts.insertAt);
// note that this is dynamically added
opts.dynamic = true;
// if we passed in options, add those to the columns object
this.columns[col] = opts;
// resize with our new column
this._cacheSize();
this._equalize();
// return new col
return $newCol;
},