forked from selsamman/amorphic-bindster
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
2440 lines (2278 loc) · 106 KB
/
index.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
/*
Copyright 2011-2013 Sam Elsamman
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/* Release history
*
* 2-5-2012 - 0.4: First release
* 5-26-2013 - 0.5: Bug Fixes and Features
*
*/
function Bindster(model, view, controller, namespace, defer)
{
document.body.style.visibility = "visible";
// Create an anchor for events
if (typeof(window['bindster_instance_count']) == 'undefined') {
window['bindster_instance_count'] = 0;
window['bindster_instances'] = [];
}
window['bindster_instances'][window['bindster_instance_count']] = this;
this.instance = "window['bindster_instances'][" + window['bindster_instance_count'] + "]"
window['bindster_instance_count']++;
this.controller = controller;
if (model)
this.setModel(model);
else
this.data = controller;
if (controller)
this.setController(controller)
this.data.none = null;
this.next_id = 1;
this.iterate_id = 1;
this.wrappers = {};
this.mappers = {};
this.wraps = {};
this.cuts = {};
this.rules = {};
this.attr = [];
this.functions = [];
this.messages = {};
this.hasErrors = false;
this.clearErrors = false;
this.bindster_error_prefix = "_field_error_";
this.bindster_temp_prefix = "_field_temp_";
this.tagDelimiter = " %% ";
this.node_id = 1;
this.cuts_id = 1;
this.set_focus = true;
this.alertCount = 0;
this.radioButtonAlert = 0;
this.attrToProp = {'class': "className", 'maxlength': "maxLength", 'for': "htmlFor"};
this.urlSuffix = null;
if (controller && typeof(controller.preRenderInitialize) == 'function')
controller.preRenderInitialize();
if (!defer)
this.start(view, namespace);
if (controller && typeof(controller.initialize) == 'function') {
controller.initialize();
controller.refresh()
}
}
Bindster.prototype.setModel = function(model)
{
this.data = model;
this.data.controller = this.controller;
this.data.c = this.controller;
if (this.controller) {
this.controller.m = this.data;
this.controller.model = this.data;
}
if (this.data && this.data.__stats) {
this.data.__stats.renders = 0;
this.data.__stats.total_render_time = 0;
this.data.__stats.last_render_time = 0;
}
}
Bindster.prototype.setController = function(controller)
{
this.controller = controller;
controller.model = this.data;
controller.m = this.data;
this.data.c = controller;
this.data.controller = controller;
controller.bindster = this;
controller.clearErrors = function(data) {
this.bindster.clearErrors = true;
this.bindster.render(data);
this.bindster.clearErrors = true;
}
controller.isError = function (propRef) {
return this.bindster.isError(propRef)
}
controller.hasErrors = function(data) {
return this.bindster.hasErrors;
}
controller.isPending = function (propRef) {
return this.bindster.isPending(propRef)
}
controller.validate = function(data) {
// A re-render can end up calling validate again
if (!this.bindster.validate) {
this.bindster.validate = true;
var node = typeof(data) == 'string' ? document.getElementById(data) : data;
node = node ? node.firstChild : node;
this.bindster.render(node);
}
return !this.hasErrors();
}
controller.render = function(data){
var node = typeof(data) == 'string' ? document.getElementById(data) : data;
node = node ? node.firstChild : node;
this.bindster.render(node);
}
controller.setError = function (objRef, propRef, error) {
if (!error) {
error = propRef;
propRef = objRef;
objRef = this.data;
}
this.bindster.setError(objRef, propRef, error);
}
controller.getErrorMessage = function(message) {
return this.bindster.getBindErrorData(null, message);
}
controller.clearError = function (objRef, propRef) {
this.bindster.clearError(objRef, propRef);
}
controller.refresh = function(defer) {
this.bindster.scheduleRender(defer);
}
controller.alert = function(msg) {
var focus = document.activeElement;
alert(msg);
focus.focus();
}
controller.attr = function(selector, attr, value) {
this.bindster.setAttr(selector, attr, value);
}
controller.rule = function(rule, value) {
this.bindster.rules[rule] = value;
}
controller.getRules = function() {
return this.bindster.rules[rule];
}
controller.set = function(tags, value) {
this.value = value;
this.bindster.eval(this.bindster.getBindAction(tags, "bindster.controller.value"), null, "controller.set");
}
controller.bindSet = function(bind, value)
{
this.value = value;
var tags = this.getTags(bind);
this.bindster.eval(this.bindster.getBindAction(tags, "bindster.controller.value"), null, "controller.set");
}
controller.bindGet = function(bind)
{
var tags = this.getTags(bind);
var bind_data = this.bindster.eval(this.bindster.resolveValue(tags.bind), null, "bind");
if (typeof(bind_data) == 'undefined')
this.bindster.throwError(null, 'bind', tags.bind + ' returned undefined');
if (tags.format)
bind_data = this.bindster.evalWithValue(tags.format, bind_data, 'format');
return bind_data;
}
controller.getTags = function(bindRef)
{
var pattrs = this.bindster.getPropAttrs(null, bindRef);
var attrs = {bind: bindRef};
for (var attr in pattrs)
{
if (attr.match(/validate|format|parse/))
attrs[attr] = this.bindster.convertValue(pattrs[attr]);
if (attr.match(/rule/)) {
var name = pattrs["rule"];
this.bindster.processRules(null, name, attrs);
}
}
return attrs;
},
controller.setIncludeURLSuffix = function (suffix) {
this.bindster.urlSuffix = suffix
},
controller.arrive = function(route) {
this.bindster.DOMTestResolve("arrival");
if (typeof(bindsterTestFrameworkRoute) == "function")
bindsterTestFrameworkRoute(route);
}
}
Bindster.prototype.alert = function(msg)
{
alert(msg)
}
Bindster.prototype.start = function(node, prefix)
{
this.renderNode = node;
if (typeof(this.renderNode) == 'string') {
this.renderNode = document.getElementById(node);
if (!this.renderNode)
this.alert('cannot find view: ' + node);
}
this.namespace_prefix = prefix ? prefix : 'b'
this.add_events_mode = true;
this.render()
this.add_events_mode = false;
if (this.bookmarks)
{
this.current_location = document.location.href;
//if (document.location.hash) Not clear why this check was here
this.checkLocation(true);
this.bookmark_interval = setInterval(this.instance + ".checkLocation()",100);
for (var ix = 0; ix < this.bookmarks.length; ++ix)
document.body.insertBefore(this.bookmarks[ix].node, document.body.firstChild);
}
}
Bindster.prototype.stop = function(node, prefix) {
if (this.bookmark_interval)
clearInterval(this.bookmark_interval);
if (this.timeout_token)
clearTimeout(this.timeout_token)
}
Bindster.prototype.render = function (node, context, parent_fingerprint, wrapped_entity, mapAttrs, cloned, iterating_entity, hasErrors)
{
var topLevel = typeof(context) == 'undefined' ? true : false;
if (topLevel) {
this.originalActionSequenceTracker = {};
var topLevelNode = node;
this.errorCount = 0;
this.hasErrors = hasErrors ? true : false;
this.last_focus_priority = 1;
if (this.data && this.data.__stats) {
this.start_render = new Date();
}
if (this.controller && typeof(this.controller.onprerender) == "function")
this.controller.onprerender.call(this.controller);
if (typeof(bindsterTestFrameworkPreRender) == "function")
bindsterTestFrameworkPreRender();
}
node = node ? node : (this.renderNode ? this.renderNode : document.body.firstChild);
context = context ? context : "";
parent_fingerprint = parent_fingerprint ? parent_fingerprint : "";
tag_string = "";
// Go through all nodes in a recursive descent
while(node)
{
var do_render = true;
var do_kill = false;
var finger_print = parent_fingerprint;
if (node.nodeType == 8 && node.data.match(/#include.*virtual="(.*)"/)) //<!--#include virtual="bindster_shared.jsp" -->
this.includeComment(RegExp.$1, node);
// ELEMENT_NODE that is not used by another bindster instance (class __bindster_view)
if (node.nodeType == 1 && (node == this.renderNode || (typeof(node.className) != 'string') || !node.className.match(/__bindster_view__/))) // Element
{
// Create our property
this.initNode(node);
// Record finger_print for our poor man's selector detector
finger_print += "/";
if (node.id)
finger_print += ('#' + node.id + ';')
var classes = node.className.split ? node.className.split(" ") : []; //SVG className is not a string
for (var ix = 0; ix < classes.length; ++ix)
if (classes[ix])
finger_print += ('.' + classes[ix] + ';');
finger_print += (' ' + node.tagName + ';');
var tags = this.getTags(node, mapAttrs, finger_print);
// Special case code to handle browser's poor handling of mixing namespaces specifically when our elements
// are in a table heirarchy. Webkit pushes them to previousSibling of the table element and Opera just refuses to nest at all.
// So we push the tags from childless iterates down into the tr and kill the iterate
if (node.tagName.match(/:iterate/i) && !this.getFirstChild(node) && node.nextSibling &&
(node.nextSibling.tagName == "TABLE" || node.nextSibling.tagName == "TR")) {
var nextSibling = node.nextSibling;
node.parentNode.removeChild(node);
node = nextSibling;
var rowNode = nextSibling.tagName == "TR" ? nextSibling :
nextSibling.getElementsByTagName("TBODY")[0].getElementsByTagName("TR")[0];
this.initNode(rowNode);
this.initNode(node);
rowNode.bindster.pushed_tags = tags;
}
// Process insertion of wraps
//if (!wrapped_entity)
var wrap = node.getAttribute("bindster_wrap") ? null : this.getWrap(finger_print);
if (wrap)
{
var nextSibling = node.nextSibling;
var parentNode = node.parentNode;
var wrapNode = wrap.outer.cloneNode(true);
var insertNode = wrapNode.getElementsByTagName('INSERT')[0] ||
wrapNode.getElementsByTagName(this.namespace_prefix.toUpperCase() +':INSERT')[0] ||
wrapNode.getElementsByTagName('INS')[0];
var className = node.className;
//node.className = className.replace(/(\S+)/g, "$1_inner")
node.setAttribute("bindster_wrap", 'wrapped');
insertNode.parentNode.insertBefore(node, insertNode); // Shove in current node into wrap
insertNode.parentNode.removeChild(insertNode); // Kill the insert marker
node = parentNode.insertBefore(wrapNode, nextSibling); // Stick the wrap in
this.initNode(node);
node.setAttribute("bindster_wrap", 'wrapper');
//node.className = className.replace(/(\S+)/g, "$1_outer");
if (className.length > 0)
node.className = node.className + (node.className.length > 0 ? ' ' : '') + className + "_outer";
this.restoreElement(node);
}
var tags = this.getTags(node, mapAttrs, finger_print); // Fetch again in case hosed by Webkit oddity code above
this.evalTags(tags, node);
// Process Mapper
if (tags.map && !node.getAttribute("bindster_map")) {
//node.appendChild(this.mappers[tags.map.name].cloneNode(true));
// Cut out existing content in case it is to be inserted in template
var child = node.firstChild;
var originalChild = child;
if (child) {
var cut = document.createElement("DIV");
while (child) {
var nextChild = child.nextSibling;
cut.appendChild(child.parentNode.removeChild(child));
child = nextChild;
}
}
this.insertElements(node, this.mappers[tags.map.name].cloneNode(true).firstChild);
if (originalChild) {
var insertNode = node.getElementsByTagName('INSERT')[0] ||
node.getElementsByTagName(this.namespace_prefix.toUpperCase() +':INSERT')[0] ||
node.getElementsByTagName('INS')[0];
if (insertNode) {
this.insertElementsBefore(insertNode.parentNode, cut.firstChild, insertNode); // Insert old content
insertNode.parentNode.removeChild(insertNode); // Kill the insert marker
} else
this.throwError(node, tags.map.name, "Must close explicitly with </" + node.tagName.toLowerCase() + ">");
}
node.setAttribute("bindster_map", "mapped");
}
// Process includes
if (tags.includeurl) {
// Nothing loaded or the wrong url is loaded
var insertNode = tags.includeinsert ? node.getElementsByTagName(tags.includeinsert.toUpperCase())[0] : node;
var url = tags.includeurl.match(/^\{(.*)\}$/) ? this.eval(RegExp.$1, null, "include", node) : tags.includeurl;
if (!this.getFirstChild(insertNode) ||
(this.getFirstChild(insertNode).tagName && this.getFirstChild(insertNode).tagName.match(/insert/i)) ||
(node.getAttribute("bindster_includeurl") && node.getAttribute("bindster_includeurl") != url))
{
var self = this;
this.includeNode(url, insertNode, tags.includeasync ? true : false,
function () {
if (tags.includewhenloaded)
self.eval(tags.includewhenloaded, null, "then", node);
if (tags.includeifloaded)
self.eval(tags.includeifloaded, null, "then", node);
});
node.setAttribute("bindster_includeurl", url);
} else {
if (tags.includeifloaded)
this.eval(tags.includeifloaded, null, "then", node);
}
}
// Process recording of mappers
if (tags.mappertag && !this.mappers[tags.mappertag]) {
this.mappers[tags.mappertag] = node.cloneNode(true);
tags = {}; // Ignore processing
do_render = false; // Don't traverse down (will be traversed after insertion)
do_kill = true; // Remove it
}
// Process recording of wrappers
if (tags.wrappername && !this.wrappers[tags.wrappername]) {
this.hideElement(node);
this.wrappers[tags.wrappername] = node;
tags = {}; // Ignore processing
do_render = false; // Don't traverse down (will be traversed after insertion)
}
// Process wrap directives to force wrapper to be the node to be hidden or shown
var hide_show_node = node;
if (node.getAttribute("bindster_wrap") == 'wrapped')
while (hide_show_node && hide_show_node.getAttribute("bindster_wrap") != 'wrapper')
hide_show_node = hide_show_node.parentNode;
// Setup an interface for controller to talk to and create the controller
if (tags.controller && !node.bindster.controller) {
var controller_interface = new BindsterControllerInterface(this, node, tags.controllerdata);
node.bindster.controller = eval("new " + tags.controller + "(controller_interface)");
this.restoreElement(node);
}
if (tags.bind)
var bind_data = this.get(tags.bind);
var hidden = false;
if (tags.test) {
if (!tags.hide || tags.hide == 'remove')
{
if (this.eval(tags.test, null, null, node))
this.insertElement(hide_show_node);
else {
this.removeElement(hide_show_node);
}
} else if (tags.onshow && tags.onhide)
{
if (this.eval(tags.test, null, null, node))
this.eval(tags.onshow, null, null, node)
else {
this.eval(tags.onhide, null, null, node)
hidden = true;
}
} else {
if (this.eval(tags.test, null, null, node))
this.restoreElement(hide_show_node);
else {
this.hideElement(hide_show_node, tags.hide);
hidden = (tags.hide == "display");
}
}
}
if (tags.onarrival)
{
if (!this.bookmarks) {
this.bookmarks = [];
}
if (node.tagName == 'A')
if (!node.getAttribute("bookmarked")) {
this.bookmarks.push(
{node: node,
hash: tags.match ? tags.match :
"^" + ((node.name && node.name.length > 0) ? node.name : (node.id ? node.id : "__domstr_start__")) + "$",
action: tags.onarrival}
);
node.setAttribute("bookmarked", true);
}
}
var skip = false;
if (hidden) // When hidden we don't process tags or descend
{
// Make sure we remember the fact that this node's parents were cloned
if (cloned)
node.bindster.cloned = 'yes';
} else {
// Iterate
var bypass = false;
var iterateon = tags.iterateon;
if (iterateon && !iterating_entity && !skip)
{
do_render = false;
var fill_data = this.get(this.resolveValue(iterateon));
if (!(fill_data instanceof Array) && tags.fill) {
fill_data = this.getValueIterator(node, tags);
iterateon += '__values__';
with ({__value__: fill_data}) {eval (this.instance + ".data." + iterateon + "= __value__")};
}
var nothing_rendered = true;
var previousNode;
// Render nodes adding more through cloning if needed
if (fill_data)
{
var iterate_id = tags.iterateid;
node.setAttribute("bindster_iterateid", iterate_id)
var counter = 0;
var loopIndex = 0; // Loop index is a 1 based index // of filtered rows
for (var ix = 0; fill_data && ix < fill_data.length; ++ix)
{
counter++;
loopIndex++;
// Create new context for setting up index values in events and binds
var new_context = (tags.iterateindex || tags.iteratewith) ?
context + (
(tags.iteratewith ? this.instance + ".set('" + tags.iteratewith + "', \""
/*+ this.instance + ".data."*/ + iterateon + "[" + ix + "]\");" : "")
+ (tags.iterateindex ? this.instance + ".set('" + tags.iterateindex + "', " + ix + ");" : "")
+ (tags.iterateloopindex ? this.instance + ".set('" + tags.iterateloopindex + "', " + loopIndex + ");" : "")
+ (tags.iteratecounter ? this.instance + ".set('" + tags.iteratecounter + "', " + counter + ");" : "")
) : context;
this.eval(new_context, null, 'with, index or counter attributes of iterate', node);
// Check filter expression
if (!tags.iteratefilter || this.eval(tags.iteratefilter, null, 'filter attribute of iterate', node ))
{
// On subsequent iterations advance to next node and clone if needed.
// We clone if there are not subsequent nodes with the same iteration id.
if (!nothing_rendered) {
if (!node.nextSibling || !node.nextSibling.getAttribute || !node.nextSibling.getAttribute("bindster_iterateid") ||
(node.nextSibling.getAttribute("bindster_iterateid") != iterate_id)) {
var new_node = node.parentNode.insertBefore(node.cloneNode(true), node.nextSibling);
this.cleanNode(new_node.firstChild);
this.initNode(new_node, true);
this.radioButtonAlert = 2; // Clone radio buttons causes original to be unchecked
new_node.bindster.cloned = "yes";
}
node = node.nextSibling;
this.initNode(node);
}
nothing_rendered = false;
// Render the node
this.restoreElement(node);
node.bindster.inwaiting = 'no';
this.render(node, new_context, finger_print, this.wrapStatus(node, wrapped_entity),
tags.map ? tags.map.attrs : mapAttrs, cloned ||
node.bindster.cloned == 'yes' || node.bindster.inwaiting == 'yes', true);
bypass = true;
}
else{
loopIndex--;
}
}
} else
if (typeof(fill_data) == "undefined")
this.throwError(node, 'iterate', 'iterate-on value is undefined');
// If nothing rendered hide first element
if (nothing_rendered) {
this.hideElement(node, 'display');
node.bindster.inwaiting = 'yes';
skip = true;
}
// Trim extra previously iterated nodes
var kill_node = node.nextSibling;
while(kill_node && kill_node.getAttribute && kill_node.getAttribute("bindster_iterateid") &&
(kill_node.getAttribute("bindster_iterateid") == iterate_id))
{
var next = kill_node.nextSibling;
kill_node.parentNode.removeChild(kill_node);
kill_node = next;
}
if (!nothing_rendered)
tags.events = {};
}
if (!bypass)
{
// Handle binding of the error fields to the view. If this a forced clear then clear the error
if (tags.binderror && !skip)
{
if (this.clearErrors)
this.clearBindError(tags.binderror, node);
var bind_error = this.getBindErrorReference(tags.binderror);
var bind_data = this.eval(bind_error, null, "binderror", node);
if (typeof(bind_data) == "object") {
bind_data = this.getBindErrorData(node, bind_data, tags.binderrordata);
this.errorCount++;
}
bind_data = bind_data && bind_data != '__pending__' ? bind_data : "";
var last_value = node.bindster.bind;
if (last_value != bind_data) {
node.innerHTML = bind_data;
node.bindster.bind = bind_data;
}
do_render = false;
} else
// Bind the model to the view (DOM) by comparing the value in the DOM to that
if (tags.bind && !skip)
{
var bind_error = this.getBindErrorReference(tags.bind);
var bind_error_value = this.get(bind_error);
var bind_error = bind_error ? (bind_error_value ? true : false) : false;
if (bind_error_value != '__pending__') {
if (!bind_error) {
// Process various tags
if (tags.fill)
{
var fill_data = this.eval(this.resolveValue(tags.fill, tags.bind, node), null, "fill", node);
var fill_using = this.eval(this.resolveValue(tags.using, tags.bind, node), null, "using", node);
if (!fill_data)
this.throwError(node, 'fill', 'cannot get data to fill' + tags.fill);
else
{
var kv = this.getSelectKeyValues(fill_data, fill_using, tags, node);
var keys = kv.keys;
var values = kv.values;
var materialize = false;
if (node.tagName == 'SELECT')
{
do_render = false;
// Iterate through the data
var child = node.firstChild;
var selected = 0;
var lastValue = null;
for (var ix = 0; ix < keys.length; ++ix)
{
var key = keys[ix];
var value = values[key];
if (value != lastValue) {
var child = child ? child : node.appendChild(document.createElement('OPTION'));
if (child.value != key) {
child.value = key;
materialize = true;
node.bindster.forceRefresh = true;
}
if (child.text != value) {
child.text = value;
materialize = true;
node.bindster.forceRefresh = true;
}
child = child.nextSibling;
lastValue = value;
}
}
// Kill extra options
if (child && child == node.firstChild)
this.hideElement(node);
else
while(child)
{
var next_node = child.nextSibling;
node.removeChild(child)
child = next_node;
materialize = true;
}
if (materialize && typeof($) == 'function') {
(function () {
var select = $(node);
select = select ? select[0] : null;
select = select ? $(select) : null;
if (select && typeof(select.material_select) == 'function')
setTimeout(function (){select.material_select()}, 0);
console.log("Calling Material Select");
})()
}
}
}
processed_tags = true;
}
var bind_data = this.eval(this.resolveValue(tags.bind), null, "bind", node);
if (typeof(bind_data) == 'undefined')
this.throwError(node, 'bind', tags.bind + ' returned undefined', node);
if (tags.format)
bind_data = this.evalWithValue(tags.format, bind_data, 'format', node);
} else
this.errorCount++;
}
var last_value = this.clearErrors ? null : node.bindster.bind;
bind_data = this.DOMTestBind(finger_print, node, tags, bind_data);
if (node.bindster.controller) {
if (!bind_error && ((node.bindster.controller.needsRender && node.bindster.controller.needsRender()) || (last_value != bind_data)))
{
node.bindster.controller.set(bind_data);
node.bindster.bind = bind_data;
}
}
else if (node.tagName == 'INPUT' && (node.type.toLowerCase() == 'text' || node.type.toLowerCase() == 'tel' || node.type.toLowerCase() == 'number' ||
node.type.toLowerCase() == 'password' || node.type.toLowerCase() == 'input' ))
{
if (tags.onenter)
this.addEvent(tags, 'onenter', this.getBindAction(tags, 'target.value') + tags.onenter);
if (tags.when)
this.addEvent(tags, 'onkeyup',this.getBindAction(tags, 'target.value'), tags.when > 0 ? tags.when : true);
this.addEvent(tags, node.type.toLowerCase() == 'number' ? 'oninput' : 'onchange', this.getBindAction(tags, 'target.value'));
this.validateValue(tags, node.value, node);
this.setFocus(tags, node);
if (!bind_error && last_value !== bind_data)
{
node.value = bind_data;
node.bindster.bind = bind_data;
this.sendToController(node.bindster);
}
}
else if (node.tagName == 'TEXTAREA')
{
this.addEvent(tags, 'onchange', this.getBindAction(tags, 'target.value'));
if (tags.when)
this.addEvent(tags, 'onkeyup', this.getBindAction(tags, 'target.value'), true);
this.validateValue(tags, node.value, node);
this.setFocus(tags, node);
if (!bind_error && last_value !== bind_data)
{
node.value = bind_data;
node.bindster.bind = bind_data;
this.sendToController(node.bindster);
}
}
else if (node.tagName == 'INPUT' && node.type.toLowerCase() == 'checkbox')
{
this.addEvent(tags, 'onclick', 'if (target.checked) { ' + this.getBindAction(tags, tags.truevalue) + '}' + 'else { ' + this.getBindAction(tags, tags.falsevalue) + '}');
this.validateValue(tags, node.checked);
this.setFocus(tags, node);
if (!bind_error && last_value !== bind_data)
{
node.bindster.bind = bind_data;
if (node.checked && bind_data == this.eval(tags.falsevalue, null, "invalid truevalue", node)) {
node.checked = false;
this.sendToController(node.bindster);
}
if (!node.checked && bind_data == this.eval(tags.truevalue, null, "invalid truevalue", node)) {
node.checked = true;
this.sendToController(node.bindster);
}
}
}
else if (node.tagName == 'INPUT' && node.type.toLowerCase() == 'radio')
{
var current_value = this.eval(tags.truevalue, null, "invalid truevalue", node) + "";
var resolve_value = "c.bindster.resolveRadioValue(target, '" + current_value + "')";
this.addEvent(tags, 'onclick', 'if (target.checked) { ' + this.getBindAction(tags, resolve_value) + '}');
this.validateValue(tags, bind_data);
this.setFocus(tags, node);
if (!bind_error && (last_value !== bind_data || this.radioButtonAlert))
{
node.bindster.bind = bind_data;
if (node.checked && (bind_data + "") != current_value) {
node.checked = false;
this.sendToController(node.bindster);
}
var self = this;
if (!node.checked && (bind_data + "") == current_value)
(function () {
var closureNode = node;
setTimeout(function () {
closureNode.checked = true;
self.sendToController(closureNode.bindster);
},0);
})()
}
}
else if (node.tagName == 'SELECT')
{
node.value; // This is a fix to keep IE from "losing" the value
var resolve_value = "c.bindster.resolveSelectValue(target)";
this.addEvent(tags, 'onchange', this.getBindAction(tags, resolve_value));
do_render = false;
//this.setFocus(tags, node);
var selected = false;
this.setFocus(tags, node);
if (!bind_error && (node.bindster.forceRefresh ? true : last_value !== bind_data)) {
child = node.firstChild;
var pleaseSelect = tags.pleaseselect ? this.evalJSTag(tags.pleaseselect) : "Select ...";
while (child) {
if (child.value == (bind_data + "") ||
bind_data && bind_data.__id__ && child.value == bind_data.__id__) { // convert booleans & objs
child.selected = true
selected = true;
node.bindster.bind = bind_data;
}
child = child.nextSibling;
}
// Add a please select ... item if no value matches and remove it if something selected
if (!selected) {
var child = node.insertBefore(document.createElement('OPTION'), node.firstChild);
child.value = bind_data !== null ? bind_data : ''; // Instead of setting a potential null value
// which becomes the literal "null" when one uses node.value, use the empty string instead
// which is a falsy
child.text = pleaseSelect;
child.selected = true;
node.selectedIndex = 0;
} else {
child = node.firstChild;
while (child) {
if (!child.selected && child.text == pleaseSelect)
node.removeChild(child);
child = child.nextSibling;
}
}
this.sendToController(node.bindster);
}
this.validateValue(tags, (!node.value && bind_data === null) ? null : node.value, node); // before validate would not see Please select ...
}
else {
if (!bind_error && (typeof(last_value) =='undefined') || (last_value != bind_data)) {
if (typeof(node.value) != 'undefined')
node.value = bind_data
else if(typeof(node.textContent) != 'undefined')
node.textContent = bind_data
else if(typeof(node.innerText) != 'undefined')
node.innerText = bind_data;
node.bindster.bind = bind_data;
this.sendToController(node.bindster);
}
do_render = false;
}
node.bindster.forceRefresh = false;
}
// Widget
if (tags.widget && !skip)
{
if (typeof(node.widget_initialized) == 'undefined') {
tags.widget.obj.call(this, node, 'initialize', tags.widget.parameters);
node.widget_initialized = true;
}
tags.widget.obj.call(this, node, 'render', tags.widget.parameters);
}
// OnPaint
if (tags.onpaint && !skip)
{
for (var ix = 0; ix < tags.onpaint.length; ++ix) {
var onpaint = tags.onpaint[ix];
var changed = false;
if (onpaint.depends.length > 0)
for (var jx = 0; jx < onpaint.depends.length; ++jx)
{
var onpaint_data = this.get(onpaint.depends[jx].value);
if (onpaint_data != node.bindster['onpaint_' + onpaint.depends[jx].name]) {
changed = true;
node.bindster['onpaint_'+ onpaint.depends[jx].name] = String(onpaint_data);
}
}
else
changed = true;
if (changed)
this.eval(onpaint.action, {prop: this.getPropAttrs(node, tags.bind)}, onpaint.tag ? onpaint.tag : 'onpaint', node);
}
}
this.processEvents(node, tags, context, cloned || node.bindster.cloned == 'yes', finger_print);
// render children
if (do_render && node.firstChild && !skip) {
this.render(node.firstChild, context, finger_print, this.wrapStatus(node, wrapped_entity),
tags.map ? tags.map.attrs : mapAttrs, cloned || node.bindster.cloned == 'yes' || node.bindster.tags_updated == 'yes');
node.bindster.cloned = "no"; // Once we process the node we don't consider it cloned
node.bindster.tags_updated = "no"; // Once we process the node we don't consider it processed
}
}
}
}
// Get next sibling to render
var nextSibling = node.nextSibling;
if (do_kill)
node.parentNode.removeChild(node);
node = nextSibling;
// For subordinate iterates we don't continue to render
if (iterating_entity)
break;
}
if (topLevel) {
this.radioButtonAlert = Math.max(this.radioButtonAlert - 1, 0);
this.hasErrors = this.errorCount > 0;
this.clearErrors = false;
this.set_focus = false;
if (this.controller && typeof(this.controller.onrender) == "function")
this.controller.onrender.call(this.controller);
if (typeof(bindsterTestFrameworkRender) == "function")
bindsterTestFrameworkRender();
if (this.data && this.data.__stats) {
this.data.__stats.last_render_time = Math.floor((new Date()).getTime() - this.start_render.getTime());
this.data.__stats.total_render_time += this.data.__stats.last_render_time;
this.data.__stats.renders ++;
}
if(!hasErrors && this.hasErrors || this.radioButtonAlert)
this.render(topLevelNode, null, null, null, null, null, null, true);
this.validate = false;
this.DOMTestResolve("render");
}
}
Bindster.prototype.sendToController = function (node_bindster) {
if (typeof(this.controller.onrendervalue) == 'function')
this.controller.onrendervalue(node_bindster.tags.bind, node_bindster.bind);
if (typeof(bindsterTestFrameworkGet) == "function")
bindsterTestFrameworkGet(node_bindster.tags.bind, node_bindster.bind);
}
Bindster.prototype.isPending = function(ref) {
var ref = this.getBindErrorReference(ref);
var data = this.eval(ref, null, "isError");
return typeof(data) != 'undefined' && data == '__pending__';
}
Bindster.prototype.resolveSelectValue = function (target)
{
if (target.bindster && target.bindster && target.bindster.tags.proptype) {
if (target.bindster.tags.proptype.__objectTemplate__ &&
target.bindster.tags.proptype.__objectTemplate__.getObject)
return target.bindster.tags.proptype.__objectTemplate__.getObject(target.value, target.bindster.tags.proptype);
else if (target.bindster.tags.proptype && target.bindster.tags.proptype == Boolean)
return target.value.match(/1|true|yes|on/) ? true : false;
}
return target.value;
}
Bindster.prototype.resolveRadioValue = function (target, value)
{
if (target.bindster && target.bindster && target.bindster.tags.proptype) {
if (target.bindster.tags.proptype.__objectTemplate__ &&
target.bindster.tags.proptype.__objectTemplate__.getObject)
return target.bindster.tags.proptype.__objectTemplate__.getObject(value, target.bindster.tags.proptype);
else if (target.bindster.tags.proptype && target.bindster.tags.proptype == Boolean)
return value.match(/1|true|yes|on/) ? true : false;
}
return value;
}
Bindster.prototype.resolveValue = function (bind_ref, bind, node) {
if (bind && this.getBindObjectReference(bind) && typeof(bind_ref) == 'function')
return bind_ref.call(this.eval(this.getBindObjectReference(bind), null, "binderror", node));
else
return bind_ref
}
Bindster.prototype.setAttr = function (selector, attr, value)
{
var str = "";
// Each property becomes an attribute but must have arrays / functions converted
if (typeof(attr) == "object" && !(attr instanceof Array)) {
for (var key in attr)
attr[key] = this.convertValue(attr[key]);
value = attr;
} else
value = this.convertValue(value);
this.attr.push({
name: attr,
value: value,
regexp: this.createSelectorRegExp(selector)
});
}
Bindster.prototype.getValueIterator = function (node, tags) {
var fill_data = this.eval(this.resolveValue(tags.fill, tags.iterateon, node), null, "fill", node);
var fill_using = this.eval(this.resolveValue(tags.using, tags.iterateon, node), null, "using", node);
if (!fill_data)
this.throwError(node, 'fill', 'cannot get data to fill' + tags.fill);
var kv = this.getSelectKeyValues(fill_data, fill_using, tags, node);
var keys = kv.keys;
var values = kv.values;
var iterator = [];
for (var ix = 0; ix < keys.length; ++ ix)
iterator.push({value: keys[ix], description: values[keys[ix]]});
return iterator;
}
Bindster.prototype.getSelectKeyValues = function (fill_data, fill_using, tags, node) {
// If an associative array (hash) create fill and using
var do_sort = false;
if (!(fill_data instanceof Array)) {
var fill_using = fill_data
fill_data = [];
for (key in fill_using)
fill_data.push(key);
do_sort = true;
}
// Run through filter functions
var keys = [];
var values = {};
for (var ix = 0; ix < fill_data.length; ++ix) {
var key = tags.fillkey ?
this.eval(tags.fillkey, {index: ix, value: fill_data[ix]}, "fillkey", node)
: fill_data[ix];
if (key != null) {
var value = fill_using ? fill_using[key] : fill_data[ix];
value = tags.fillvalue ?
this.eval(tags.fillvalue, {key: key, value: value, index: ix}, "fillvalue", node)
: value;
if (value != null) {
keys.push(key);
values[key] = value;
}
}
}
if (do_sort && tags.sort !== 'none') {