-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathViewBridge.js
More file actions
1439 lines (1114 loc) · 41 KB
/
ViewBridge.js
File metadata and controls
1439 lines (1114 loc) · 41 KB
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
if (!window.rhubarb) {
window.rhubarb = {};
}
window.rhubarb.registeredLeaves = {};
window.rhubarb.viewBridgeClasses = {};
window.rhubarb.spawn = function (spawnSettings, viewIndex, parentleafPath) {
var viewBridgeClass = window.rhubarb.viewBridgeClasses[spawnSettings.ViewBridgeClass];
if (viewBridgeClass.spawn) {
var element = viewBridgeClass.spawn(spawnSettings, viewIndex, parentleafPath);
var bridge = new viewBridgeClass(element);
for (var i in spawnSettings) {
bridge.model[i] = spawnSettings[i];
}
return element;
}
return false;
};
/**
* A base class for the client side extension of server side Presenters.
*
* This includes low level plumbing for talking through AJAX to the server presenters without
* using jQuery. By not relying on jQuery we ensure that we aren't going to be upset by
* jQuery version conflicts and our foot print is smaller.
*
* @constructor
* @param leafPath
* @param onCreatedCallback
*/
function ViewBridge(leafPath, onCreatedCallback) {
if (arguments.length == 0) {
return;
}
if (typeof leafPath == "string") {
this.leafPath = leafPath;
this.viewNode = document.getElementById(this.leafPath);
}
else {
this.viewNode = leafPath;
this.leafPath = this.viewNode.id;
}
this.leafName = this.leafPath;
if (this.viewNode) {
if (this.viewNode.viewBridge) {
// This element already has a viewBridge attached. For some reason this bridge is being
// constructed a second time for the same
// return;
}
if (this.viewNode.attributes["leaf-name"]) {
this.leafName = this.viewNode.attributes["leaf-name"].value;
}
this.viewNode.viewBridge = this;
}
if (leafPath == "host") {
this.leafPath = this.leafName;
}
this.serverEventResponseHandlers = {};
this.clientEventHandlers = {};
this.model = [];
if (this.viewNode) {
this.host = ( this.viewNode.className.indexOf("event-host") > -1 );
}
this.loadState();
this.eventHostClassName = "";
if (document.getElementById(this.leafPath + 'EventHost')) {
this.eventHostClassName = document.getElementById(this.leafPath + 'EventHost').value;
this.host = true;
}
if (this.viewNode && this.viewNode.serverEventResponseHandlers) {
this.serverEventResponseHandlers = this.viewNode.serverEventResponseHandlers;
}
this.attachDomChangeEventHandler();
if (onCreatedCallback){
onCreatedCallback();
}
this.registerLeaf();
this.onReady();
}
/**
* Called when the view bridge has been instantiated and the creation callback has been called.
*
* Under normal conditions all children should be ready at this point.
*/
ViewBridge.prototype.onReady = function() {
};
ViewBridge.prototype.selectAndIterateElements = function(selector, callback) {
var nodes = this.viewNode.querySelectorAll(selector);
for(var i = 0; i < nodes.length; i++){
callback(nodes[i]);
}
};
ViewBridge.prototype.submitForm = function () {
var host = this.findEventHost();
host.viewNode.parentNode.submit();
};
ViewBridge.prototype.hasValue = function () {
if (!this.viewNode) {
return false;
}
var hasValue = false;
var nodeTagName = this.viewNode.tagName.toLowerCase();
if (nodeTagName == "input" || nodeTagName == "select" || nodeTagName == "textarea") {
hasValue = true;
if (this.viewNode.type && ( this.viewNode.type.toLowerCase() == "button" ||
this.viewNode.type.toLowerCase() == "submit" ||
this.viewNode.type.toLowerCase() == "image" )) {
hasValue = false;
}
}
return hasValue;
};
/**
* Override to attach the DOM listeners required so you can call the valueChanged() method.
*/
ViewBridge.prototype.attachDomChangeEventHandler = function (triggerChangeEvent) {
if (!triggerChangeEvent) {
triggerChangeEvent = false;
}
var self = this;
var callBack = function () {
self.valueChanged();
};
if (!this.viewNode.addEventListener) {
this.viewNode.attachEvent("onchange", callBack);
}
else {
// Be interested in a changed event if there is one.
this.viewNode.addEventListener('change', callBack, false);
}
if (triggerChangeEvent) {
callBack();
}
};
ViewBridge.prototype.getViewIndex = function () {
var pattern = /\((\d+)\)$/;
var match = pattern.exec(this.viewNode.id);
if (match) {
return match[1];
}
return false;
};
/**
* A static function to allow creation of a view bridge entirely from data provided
*
* This will return a DOMElement that can be inserted into the DOM just as if it always existed.
*
* @param spawnData
* @param [index]
* @param [parentleafPath]
*/
ViewBridge.spawn = function (spawnData, index, parentleafPath) {
};
/**
* Sets common attributes on a newly spanned view bridge such as id, name
* and presenter-name.
*
* @param spawnData
* @param node
* @param [index]
*/
ViewBridge.applyStandardAttributesToSpawnedElement = function (node, spawnData, index, parentleafPath) {
var id = parentleafPath ? parentleafPath + '_' + spawnData.PresenterName : spawnData.leafPath;
if (index !== null && index !== false && (typeof index !== "undefined")) {
id += "(" + index + ")";
}
node.id = id;
node.setAttribute("name", id);
node.setAttribute("presenter-name", spawnData.PresenterName);
};
ViewBridge.prototype.registerLeaf = function () {
window.rhubarb.registeredLeaves[this.leafPath] = this;
this.onRegistered();
this.attachEvents();
};
ViewBridge.prototype.onReattached = function () {
};
ViewBridge.prototype.onRegistered = function () {
};
ViewBridge.prototype.onParentsReady = function () {
if (!this.eventHost) {
this.eventHost = this.findEventHost();
}
};
ViewBridge.prototype.findContainingViewBridge = function () {
var parent = this.viewNode.parentNode;
while (parent) {
if (parent.viewBridge) {
return parent.viewBridge;
}
parent = parent.parentNode;
}
return false;
};
ViewBridge.prototype.getContainingViewBridge = ViewBridge.prototype.findContainingViewBridge;
ViewBridge.prototype.findParent = ViewBridge.prototype.findContainingViewBridge;
ViewBridge.prototype.attachServerEventResponseHandlerTo = function (domElement, event, callback) {
if (domElement.viewBridge) {
domElement.ViewBridge.attachServerEventResponseHandler(event, callback);
}
else {
if (!domElement.serverEventResponseHandlers) {
domElement.serverEventResponseHandlers = {};
}
if (!domElement.serverEventResponseHandlers[event]) {
domElement.serverEventResponseHandlers[event] = [];
}
domElement.serverEventResponseHandlers[event][domElement.serverEventResponseHandlers[event].length] = callback;
}
};
/**
* Searches with the inner DOM of the viewBridge looking for a sub viewBridge with the matching name.
*
* This differs from findViewBridge in that it must be a direct child of the container. In other words
* grand children or further removed descendants would not match.
*
* @param presenterName
* @param [viewIndex] If you're looking for an indexed view bridge, you'll need to pass it's index here. If you don't
* you'll get the first it comes across.
*/
ViewBridge.prototype.findChildViewBridge = function (presenterName, viewIndex) {
var leafPaths = [];
for (var i in window.rhubarb.registeredLeaves) {
leafPaths.push(i);
}
leafPaths.sort();
var thisleafPath = this.leafPath + '_';
for (i in leafPaths) {
var presenter = window.rhubarb.registeredLeaves[leafPaths[i]];
if (presenter.leafName == presenterName) {
var leafPath = presenter.leafPath;
// Check the viewBridge we're considering is a child of this one.
if (leafPath.indexOf(thisleafPath) == 0) {
if (leafPath.replace(thisleafPath, '').indexOf("_") == -1) {
return presenter;
}
}
}
}
return false;
};
ViewBridge.prototype.findViewBridgesWithIndex = function(leafName) {
var leafPaths = [];
for (var i in window.rhubarb.registeredLeaves) {
leafPaths.push(i);
}
leafPaths.sort();
var thisleafPath = this.leafPath + '_';
var leaves = [];
for (i in leafPaths) {
var leaf = window.rhubarb.registeredLeaves[leafPaths[i]];
if (leaf.leafName == leafName) {
// Check the viewBridge we're considering is a child of this one.
if (leaf.leafPath.indexOf(thisleafPath) == 0) {
leaves.push(leaf);
}
}
}
return leaves;
};
/**
* Searches with the inner DOM of the viewBridge looking for a sub viewBridge with the matching name
*
* @param presenterName
* @param [viewIndex] If you're looking for an indexed view bridge, you'll need to pass its index here. If you don't
* you'll get the first it comes across.
*/
ViewBridge.prototype.findViewBridge = function (presenterName, viewIndex) {
var leafPaths = [];
for (var i in window.rhubarb.registeredLeaves) {
leafPaths.push(i);
}
leafPaths.sort();
var thisleafPath = this.leafPath + '_';
for (i in leafPaths) {
var presenter = window.rhubarb.registeredLeaves[leafPaths[i]];
if (presenter.leafName == presenterName) {
// This viewBridge is indexed, so check the viewBridge we're considering matches this one's index
// Check the viewBridge we're considering is a child of this one.
if (presenter.leafPath.indexOf(thisleafPath) == 0) {
return presenter;
}
}
}
return false;
};
ViewBridge.prototype.clearServerEventResponseHandlers = function (event) {
this.serverEventResponseHandlers = {};
};
ViewBridge.prototype.attachServerEventResponseHandler = function (event, callback) {
if (!this.serverEventResponseHandlers[event]) {
this.serverEventResponseHandlers[event] = [];
}
this.serverEventResponseHandlers[event][this.serverEventResponseHandlers[event].length] = callback;
};
/**
* Attaches a callback to be triggered when an event is raised on the client.
*
* This is raised for events that are triggered using raiseServerEvent however this callback is
* triggered first, before the server is passed the event.
*
* @param event
* @param callback
*/
ViewBridge.prototype.attachClientEventHandler = function (event, callback) {
if (!this.clientEventHandlers[event]) {
this.clientEventHandlers[event] = [];
}
this.clientEventHandlers[event][this.clientEventHandlers[event].length] = callback;
};
ViewBridge.prototype.removeClientEventHandler = function (event, callback) {
if (!this.clientEventHandlers[event]) {
return;
}
var index = this.clientEventHandlers[event].indexOf(callback);
if (index != -1) {
this.clientEventHandlers[event].splice(index, 1);
}
};
ViewBridge.prototype.removeClientEventHandlers = function (event) {
this.clientEventHandlers[event] = [];
};
/**
* Loads the state of the viewBridge model
*/
ViewBridge.prototype.loadState = function () {
var path = this.leafPath;
if (!document.getElementById(path + 'State') || ( document.getElementById(path + 'State').value == '' )) {
return;
}
this.model = JSON.parse(document.getElementById(path + 'State').value);
if (document.getElementById(this.leafPath)) {
if (document.getElementById(this.leafPath).className == "host") {
this.host = true;
}
}
this.onStateLoaded();
};
/**
* Loads the state of the viewBridge model
*/
ViewBridge.prototype.saveState = function () {
if (!document.getElementById(this.leafPath + 'State')) {
return;
}
var json = JSON.stringify(this.model);
document.getElementById(this.leafPath + 'State').value = json;
return json;
};
ViewBridge.prototype.onStateLoaded = function () {
};
ViewBridge.prototype.getSubLeaves = function () {
var subPresenters = [];
for (var subPath in window.rhubarb.registeredLeaves) {
if (subPath == this.leafPath) {
// We are not a child of ourselves
continue;
}
if (subPath.indexOf(this.leafPath + "_") == 0) {
subPresenters[subPresenters.length] = window.rhubarb.registeredLeaves[subPath];
}
}
return subPresenters;
};
ViewBridge.prototype.onSubLeafValueChanged = function () {
};
ViewBridge.prototype.subLeafValueChanged = function (viewBridge, newValue) {
this.onSubLeafValueChanged.apply(this, arguments);
var container = this.getContainingViewBridge();
if (container) {
container.subLeafValueChanged(viewBridge, newValue);
}
};
ViewBridge.prototype.valueChanged = function () {
var newValue = this.getValue();
var container = this.getContainingViewBridge();
if (container) {
container.subLeafValueChanged(this, newValue);
}
this.raiseClientEvent("ValueChanged", this, newValue);
};
/**
* Returns value for the viewBridge if appropriate.
*
* Used to build models for client side validation.
*
* @returns {string}
*/
ViewBridge.prototype.getValue = function () {
if (this.viewNode && this.viewNode.value) {
return this.viewNode.value;
}
return "";
};
ViewBridge.prototype.getSerializableValue = function () {
return this.getValue();
};
ViewBridge.prototype.getDisplayView = function () {
return this.getValue();
};
ViewBridge.prototype.setValue = function (value) {
if (this.viewNode && ( "value" in this.viewNode )) {
this.viewNode.value = value;
}
};
ViewBridge.prototype.getSubLeafValues = function () {
// Get all the values from all the sub presenters to build our model to validate.
var subPresenters = this.getSubLeaves();
var model = {};
for (var i in subPresenters) {
var subPresenter = subPresenters[i];
model[subPresenter.leafName] = subPresenter.getValue();
}
return model;
};
ViewBridge.prototype.validate = function (validator) {
var model = this.getSubLeafValues();
var placeholders = document.getElementsByTagName("em");
for (var i = 0; i < placeholders.length; i++) {
if (placeholders[i].className.indexOf("validation-placeholder") > -1) {
placeholders[i].innerHTML = "";
placeholders[i].className = "validation-placeholder";
}
}
try {
validator.validate(model);
} catch (error) {
// For now we simply try and update any matching placeholders with the relevant error.
error.applyToPlaceholders(this.viewNode);
return error;
}
return true;
};
/**
* Override this to attach any event handlers.
*
* Called once the state has been restored.
*/
ViewBridge.prototype.attachEvents = function () {
};
/**
* Searches through the parents of the viewBridge to find the host viewBridge element.
*
* @return {*}
*/
ViewBridge.prototype.findEventHost = function () {
var selfNode = document.getElementById(this.leafPath);
while (selfNode) {
var testNode = selfNode;
selfNode = selfNode.parentNode;
var className = ( testNode.className ) ? testNode.className : "";
if (className.indexOf("event-host") == 0 || className.indexOf("event-host") > 0) {
if (!testNode.viewBridge) {
if (!testNode.id) {
testNode.id = "event-host";
}
new window.ViewBridge(testNode.id);
if (testNode.className.indexOf("event-host") == 0 || testNode.className.indexOf("event-host") > 0) {
testNode.viewBridge.host = true;
}
}
}
if (testNode.viewBridge && testNode.viewBridge.host && testNode.className.indexOf("configured") == -1) {
return testNode.viewBridge;
}
}
return false;
};
/**
* Raises an event for consumption only by listeners on the client.
*
* @param eventName
*/
ViewBridge.prototype.raiseClientEvent = function (eventName) {
if (!this.clientEventHandlers[eventName]) {
return;
}
var argumentsArray = [];
for (var i = 1; i < arguments.length; i++) {
argumentsArray[i - 1] = arguments[i];
}
var lastResponse;
for (i in this.clientEventHandlers[eventName]) {
var callback = this.clientEventHandlers[eventName][i];
lastResponse = callback.apply(callback, argumentsArray);
}
return lastResponse;
};
ViewBridge.prototype.sendFileAsServerEvent = function (eventName, file, onProgress, onComplete, onFailure) {
if (!this.eventHost) {
this.eventHost = this.findEventHost();
}
// If we're not the host we need to find the host and call it's raise event instead.
var hostPresenter = this.eventHost;
var self = this;
var xmlhttp = this.createXmlHttpRequest();
var presenter = this;
xmlhttp.upload.onprogress = onProgress;
// Attach the call back wrapper for the AJAX post.
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
document.body.className = document.body.className.replace(" event-processing", "");
presenter.onEventProcessingFinished();
if (xmlhttp.responseXML != null) {
self.parseEventResponse(eventName, xmlhttp.status, xmlhttp.responseXML, onComplete, onFailure);
} else {
onFailure();
}
}
};
var target = this.leafPath;
var index = this.getViewIndex();
if (hostPresenter) {
var formData = new FormData();
formData.append("_leafEventName", eventName);
formData.append("_leafEventTarget", target);
if (hostPresenter.eventHostClassName != "") {
formData.append("_leafEventClass", hostPresenter.eventHostClassName);
formData.append("_leafEventleafPath", hostPresenter.leafPath);
}
var csrfTokenElements = this.eventHost.viewNode.parentElement.getElementsByClassName('js-csrf_tk');
if (csrfTokenElements.length > 0) {
var csrfToken = csrfTokenElements[0].value;
formData.append('csrf_tk', csrfToken);
}
formData.append(this.leafPath, file);
// Add all hidden State inputs on the page to ensure event processing can
// recover the original state.
var inputs = hostPresenter.viewNode.getElementsByTagName("input");
for (i = 0; i < inputs.length; i++) {
var input = inputs[i];
var type = input.type;
if (type.toLowerCase() == "hidden") {
formData.append(input.name, input.value);
}
}
xmlhttp.open("POST", window.location.href, true);
xmlhttp.setRequestHeader('Accept', 'application/leaf');
xmlhttp.setRequestHeader('X-Requested-With', 'xmlhttprequest');
xmlhttp.send(formData);
document.body.className = document.body.className + " event-processing";
presenter.onEventProcessingStarted();
}
return xmlhttp;
};
ViewBridge.prototype.raisePostBackEvent = function (eventName) {
var argumentsArray = [];
var callback = false;
// Get the arguments into a proper array while stripping any closure found to become a callback.
for (var i = 0; i < arguments.length; i++) {
argumentsArray[i] = arguments[i];
if (arguments[i] instanceof Function) {
callback = arguments[i];
}
}
// Give the client side a first look at the event.
this.raiseClientEvent.apply(this, argumentsArray);
// Standardise the arguments list by ensuring the targeted viewBridge is the last parameter.
var targetViewBridge;
if (argumentsArray[argumentsArray.length - 1] instanceof ViewBridge) {
targetViewBridge = argumentsArray[argumentsArray.length - 1];
}
else {
targetViewBridge = this;
argumentsArray[argumentsArray.length] = targetViewBridge;
}
if (!this.eventHost) {
this.eventHost = this.findEventHost();
}
// If we're not the host we need to find the host and call it's raise event instead.
var hostPresenter = this.eventHost;
var target = targetViewBridge.leafPath;
var index = targetViewBridge.getViewIndex();
if (index) {
target = target.replace(/\(\d+\)$/, '');
}
if (hostPresenter) {
var createOrFindHiddenInput = function (inputName) {
if (document.getElementById(inputName)) {
return document.getElementById(inputName);
} else {
var newInput = document.createElement('input');
newInput.type = "hidden";
newInput.id = inputName;
newInput.name = inputName;
hostPresenter.viewNode.appendChild(newInput);
return newInput;
}
};
var eventNameInput = createOrFindHiddenInput("_leafEventName");
var eventTargetInput = createOrFindHiddenInput("_leafEventTarget");
var eventTargetIndexInput = createOrFindHiddenInput("_leafTargetIndex");
var eventClassInput = createOrFindHiddenInput("_leafClass");
var eventleafPathInput = createOrFindHiddenInput("_leafleafPath");
var eventArgumentsInput = createOrFindHiddenInput("_leafEventArgumentsJson");
eventNameInput.value = eventName;
eventTargetInput.value = target;
if (index) {
eventTargetIndexInput.value = index;
}
if (hostPresenter.eventHostClassName != "") {
eventClassInput.value = hostPresenter.eventHostClassName;
eventleafPathInput.value = hostPresenter.leafPath;
}
var flatArguments = [];
for (i = 1; i < arguments.length; i++) {
var argument = arguments[i];
if (!(argument instanceof ViewBridge ) && !( argument instanceof Function )) {
flatArguments.push(argument);
}
}
eventArgumentsInput.value = JSON.stringify(flatArguments);
// Our parent should be the form tag.
hostPresenter.viewNode.parentNode.submit();
}
};
/**
* Raises an event via an XMLHttpRequest
*
* If this is not the host viewBridge we bubble the event up to the host ViewBridge.
*
* @param eventName The name of the event to trigger
* @param targetViewBridge The name of the viewBridge the event is being triggered for
*/
ViewBridge.prototype.raiseServerEvent = function (eventName) {
var self = this;
var argumentsArray = [];
var successCallback = false;
var failureCallback = false;
// Get the arguments into a proper array while stripping any closure found to become a callback.
for (var i = 0; i < arguments.length; i++) {
if (arguments[i] instanceof Function) {
if (!successCallback) {
successCallback = arguments[i];
} else if (!failureCallback) {
failureCallback = arguments[i];
}
} else {
argumentsArray[i] = arguments[i];
}
}
// Standardise the arguments list by ensuring the targeted viewBridge is the last parameter.
var targetViewBridge;
if (argumentsArray[argumentsArray.length - 1] instanceof ViewBridge) {
targetViewBridge = argumentsArray[argumentsArray.length - 1];
}
else {
targetViewBridge = this;
argumentsArray[argumentsArray.length] = targetViewBridge;
}
if (!this.eventHost) {
this.eventHost = this.findEventHost();
}
// If we're not the host we need to find the host and call it's raise event instead.
var hostPresenter = this.eventHost;
var xmlhttp = this.createXmlHttpRequest();
// Attach the call back wrapper for the AJAX post.
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
document.body.className = document.body.className.replace(" event-processing", "");
self.onEventProcessingFinished();
if (xmlhttp.responseXML != null) {
targetViewBridge.parseEventResponse(eventName, xmlhttp.status, xmlhttp.responseXML, successCallback, failureCallback);
} else if (self.isFailureCode(xmlhttp.status) && failureCallback) {
failureCallback(xmlhttp.responseText, xmlhttp.status);
}
}
};
var target = targetViewBridge.leafPath;
var index = targetViewBridge.getViewIndex();
if (hostPresenter) {
var formData = hostPresenter.findInputsAndSerialize(hostPresenter.viewNode);
formData += "_leafEventName=" + eventName + "&_leafEventTarget=" + target;
formData += "&_leafEventState=" + hostPresenter.saveState();
if (hostPresenter.eventHostClassName != "") {
formData += "&_leafEventClass=" + hostPresenter.eventHostClassName + "&_leafEventleafPath=" + hostPresenter.leafPath;
}
for (i = 1; i < arguments.length; i++) {
var argument = arguments[i];
if (!(argument instanceof ViewBridge ) && !( argument instanceof Function )) {
argument = JSON.stringify(argument);
formData += "&_leafEventArguments[]=" + encodeURIComponent(argument);
}
}
xmlhttp.open("POST", window.location.href, true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.setRequestHeader('Accept', 'application/leaf');
xmlhttp.setRequestHeader('X-Requested-With', 'xmlhttprequest');
xmlhttp.send(formData);
document.body.className += " event-processing";
targetViewBridge.onEventProcessingStarted();
}
return xmlhttp;
};
ViewBridge.prototype.onEventProcessingStarted = function () {
if (this.viewNode) {
this.viewNode.className += " my-event-processing";
}
};
ViewBridge.prototype.onEventProcessingFinished = function () {
if (this.viewNode) {
this.viewNode.className = this.viewNode.className.replace(" my-event-processing", "");
}
};
/**
* Creates a new XMLHttpRequest object
*
* Provides an opportunity to configure the XMLHttpRequest object if required.
*
* @returns {XMLHttpRequest}
*/
ViewBridge.prototype.createXmlHttpRequest = function () {
return new XMLHttpRequest();
};
ViewBridge.prototype.loadJson = function (url, callback) {
var xmlhttp = this.createXmlHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callback(JSON.parse(xmlhttp.responseText));
}
};
xmlhttp.open("GET", url, true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.setRequestHeader('Accept', 'application/json');
xmlhttp.setRequestHeader('X-Requested-With', 'xmlhttprequest');
xmlhttp.send();
};
ViewBridge.prototype.isSuccessCode = function (httpResponseCode) {
return httpResponseCode >= 200 && httpResponseCode < 300;
};
ViewBridge.prototype.isFailureCode = function (httpResponseCode) {
return httpResponseCode >= 400 && httpResponseCode < 600;
};
/**
* Parses the raw xml response from the AJAX postback.
*
* We look both for <htmlupdate> tags and update the relevant elements and
* <eventresponse> tags to call event handlers on the client.
*
* @param eventName
* @param responseCode
* @param responseXml
* @param successCallback
* @param failureCallback
*/
ViewBridge.prototype.parseEventResponse = function (eventName, responseCode, responseXml, successCallback, failureCallback) {
var updateElements = responseXml.getElementsByTagName("htmlupdate");
var eventResponses = responseXml.getElementsByTagName("eventresponse");
var scripts = responseXml.getElementsByTagName("script");
var models = responseXml.getElementsByTagName("model");
var eventsToRaise = responseXml.getElementsByTagName("event");
var content, target, callback;
if (this.isSuccessCode(responseCode)) {
callback = successCallback;
} else if (this.isFailureCode(responseCode)) {
callback = failureCallback;
} else {
console.log('Unhandled response code: ' + responseCode);
}
for (var i = 0; i < updateElements.length; i++) {
var element = updateElements[i];
var targetId = element.getAttribute("id");
content = ( element.textContent ) ? element.textContent : element.text;
var targetElement = document.getElementById(targetId);
if (targetElement) {
if (targetElement.viewBridge) {
targetElement.viewBridge.onBeforeUpdateDomUpdateFromServer();
}
var shim = document.createElement("div");
shim.innerHTML = content;
targetElement.innerHTML = shim.children[0].innerHTML;
if (targetElement.viewBridge) {
targetElement.viewBridge = undefined;