-
Notifications
You must be signed in to change notification settings - Fork 3
/
Dynamo_Client_Store_web_store.war_shared_js_pageLayout_layout-container.js.html
executable file
·1319 lines (1182 loc) · 54.3 KB
/
Dynamo_Client_Store_web_store.war_shared_js_pageLayout_layout-container.js.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JSDoc: Source: Dynamo/Client/Store/web/store.war/shared/js/pageLayout/layout-container.js</title>
<script src="scripts/prettify/prettify.js"> </script>
<script src="scripts/prettify/lang-css.js"> </script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
</head>
<body>
<div id="main">
<h1 class="page-title">Source: Dynamo/Client/Store/web/store.war/shared/js/pageLayout/layout-container.js</h1>
<section>
<article>
<pre class="prettyprint source"><code>/**
* @fileoverview Controlling class that maintains the processing and
* flow of a page. Defines the LayoutContainer view model.
*
*/
/*global $ */
/*global require */
define(
//-------------------------------------------------------------------
// PACKAGE NAME
//-------------------------------------------------------------------
'pageLayout/layout-container',
//-------------------------------------------------------------------
// DEPENDENCIES
//-------------------------------------------------------------------
[ 'knockout',
'pageLayout/data',
'pageLayout/layout',
'pageLayout/region',
'pageLayout/widget',
'pageLayout/cart',
'pageLayout/order',
'pageLayout/layout-mapping',
'pageLayout/simple-cache',
'pageLayout/context-handler',
'pageLayout/view-model-builder',
'pageLayout/search',
'pageLayout/shippingmethods',
'pageLayout/payment-auth-response',
'pageLayout/user',
'pageLayout/product',
'pageLayout/space',
'pageViewTracker',
'viewModels/paymentDetails',
'pubsub',
'CCi18n',
'ccConstants',
'ccLogger',
'jquery',
'notifier',
'spinner',
'pageLayout/site',
'storageApi',
'sfExceptionHandler',
'ccStoreServerLogger',
'viewportHelper',
'navigation',
'ccRestClient'
],
//-------------------------------------------------------------------
// MODULE DEFINTIION
//-------------------------------------------------------------------
function (ko, ServerData, LayoutViewModel, RegionViewModel, WidgetViewModel,
CartViewModel, OrderViewModel, LayoutMapping, Cache, ContextHandler,
ViewModelBuilder, SearchViewModel, ShippingMethodsViewModel, PaymentAuthResponseViewModel,
UserViewModel, ProductViewModel, SpaceViewModel, pageViewTracker, PaymentDetails, PubSub, CCi18n, CCConstants,
ccLogger, $, notifier, spinner, SiteViewModel, storageApi, ExceptionHandler, StoreServerLogger, viewportHelper, navigation, ccRestClient) {
"use strict";
//-----------------------------------------------------------------
//Class definition & member variables (the constructor)
//-----------------------------------------------------------------
/**
* Creates an LayoutContainer object. LayoutContainer controls the flow of a page including how to build
* a {@link LayoutViewModel|layout}, how to load data, and managing contextual data. All
* {@link WidgetViewModel|widgets} are constructed via the LayoutContainer.
*
* @param {Object} adapter The current context of the page.
* @param {String} basePath The URL path to this widget.
*
* @private
* @class
* @name LayoutContainer
* @property {LayoutMapping} layoutMapping The mapping used to map a layout.
* @property {WidgetEditorViewModel} editor The widget editor responsible for editing widgets.
* @property {SimpleCache} cache The Cache used to store retrieved records.
* @property {ContextHandler} contextHandler The context handler used to manage contextual data.
* @property {ViewModelBuilder} viewModelBuilder The view model builder used to convert json to view models.
*/
function LayoutContainer(adapter, basePath) {
var self = this;
this.isPreview;
this.layoutMapping = new LayoutMapping(this);
this.basePath = basePath;
this.adapter = adapter;
this.cache = new Cache();
this.widgetCache = new Cache();
this.contextHandler = new ContextHandler();
this.viewModelBuilder = ViewModelBuilder;
this.contextDataSet = $.Deferred();
this.contextDataSetSubscriber = this.contextDataSet.promise();
this.networkErrorMessage;
this.networkErrorReloadText;
self.storeServerLog = StoreServerLogger.getInstance();
this.currentPage = null;
// Widgets that are currently being initialized (if any)
this.pendingWidgets = ko.observableArray().extend({ deferred: true });
$.Topic(PubSub.topicNames.PAGE_VIEW_CHANGED).subscribe(self.pageViewChanged.bind(self));
$.Topic(PubSub.topicNames.PAGE_CONTEXT_CHANGED).subscribe(self.pageContextChanged.bind(self));
$.Topic(PubSub.topicNames.PAGE_PARAMETERS_CHANGED).subscribe(self.pageParametersChanged.bind(self));
$.Topic(PubSub.topicNames.PAGE_READY).subscribe(self.pageReady.bind(self));
$.Topic(PubSub.topicNames.RECORD_PAGINATION_PAGE_CHANGE).subscribe(self.pageReady.bind(self));
$.Topic(PubSub.topicNames.USER_NETWORK_ERROR).subscribe(self.networkError.bind(self));
// Exception handing
var clientDebugMode = true;
if (clientDebugMode) {
this.exceptionHandler = new ExceptionHandler();
if (this.exceptionHandler.subscribe) {
this.exceptionHandler.subscribe();
}
}
return (this);
}
//------------------------------------------------------------------
// Class functions
//------------------------------------------------------------------
/**
* Returns a view model builder for the passed in type, or creates a default builder if none found.
*
* @function
* @name LayoutContainer#getViewModelBuilder
* @param {string} type The type of object for which to return a builder.
* @returns {ViewModelBuilder} View model builder for `type'.
*/
LayoutContainer.prototype.getViewModelBuilder = function(type) {
var builder = this.viewModelBuilder[type];
if(builder == null) {
builder = {
scope: 'page',
cacheable: false,
load: true,
create: true
};
}
return builder;
};
/**
* Walk the properties in "global" and "page" scope.
* For each property add it to the context handler so that
* it can be available for widgets to enjoy.
*
* @private
* @function
* @name LayoutContainer#setContextData
* @param {Object} serverData
*/
LayoutContainer.prototype.setContextData = function(serverData) {
//var serverData = layoutViewMapping.data,
var topLevelProps, propsIdx = 0,
property;
//if (!serverData) { return; }
var self = this;
var processServerData = function() {
topLevelProps = ['global', 'page'];
for (propsIdx = 0; propsIdx < topLevelProps.length; propsIdx++) {
for (property in serverData[topLevelProps[propsIdx]]) {
if (serverData[topLevelProps[propsIdx]].hasOwnProperty(property) && property !== "__ko_mapping__") {
self.loadCurrentFromJSON(property,
serverData[topLevelProps[propsIdx]][property], serverData);
}
}
}
// Context data all set. Dependencies can execute now
self.contextDataSet.resolve();
// Reset the deferred stuff as it seems to not quite work on IE if you dont...
self.contextDataSet = $.Deferred();
self.contextDataSetSubscriber = self.contextDataSet.promise();
};
// Setup locale before building any view models
var localeFromServer = serverData['global']['locale'];
if (localeFromServer && localeFromServer !== null) {
CCi18n.setLocaleOnce(localeFromServer,processServerData);
} else {
// we don't have a locale, keep on going
processServerData();
}
};
/**
* Listens for PAGE_CONTEXT_CHANGED events and
* requests only data from the server. When data is
* return it sets up context variables according to the
* returned data.
*
* @private
* @function
* @name LayoutContainer#pageContextChanged
* @param {string} data.contextId New context id.
* @param {string} data.pageId URL to request.
*/
LayoutContainer.prototype.pageContextChanged = function (data) {
var self = this;
self.currentPage = data;
var requestURL = data.pageId;
var params = {};
params[CCConstants.PAGE_PARAM] = data.contextId;
params[CCConstants.DATA_ONLY] = true;
this.load('layout', requestURL, params,
// Callback for load result
function (result) {
// Update context variables
self.setContextData(result.data);
self.updatePageEventData(result.data, data);
if (result.data && result.data.global && result.data.global.site) {
if (result.data.global.site.tenantId) {
pageViewTracker.tenantId(result.data.global.site.tenantId);
}
}
// Do we need to publish here? Sure...
$.Topic(PubSub.topicNames.PAGE_METADATA_CHANGED).publish(result);
$.Topic(PubSub.topicNames.PAGE_READY).publish(data);
},
self.handleServerError
);
};
/**
* Adds the page repository id from the server context data to the page event data being
* passed around.
*
* @private
* @function
* @name LayoutContainer#updatePageEventData
* @param {Object} pServerData
* @param {Object} pPageEventData
*/
LayoutContainer.prototype.updatePageEventData = function(pServerData, pPageEventData) {
if (pServerData.page && pServerData.page.repositoryId) {
pPageEventData.pageRepositoryId = pServerData.page.repositoryId;
}
};
/**
* Callback function invoked if an error is returned after a request.
*
* @private
* @function
* @name LayoutContainer#handleServerError
* @param {Object} result Result object returned from server.
*/
LayoutContainer.prototype.handleServerError = function (result) {
$.Topic(PubSub.topicNames.PAGE_LAYOUT_SERVER_ERROR).publish(result);
};
/**
* Listens for PAGE_PARAMETERS_CHANGED events. When data is returned it
* pushes a PubSub PAGE_PARAMETERS event for transferring the data to
* appropriate location for handling the data
* e.g. when the view is "searchresults"
* the data is sent to searchViewModel for creation of a
* new search with the data provided
*
* @private
* @function
* @name LayoutContainer#pageParametersChanged
* @param {Object} pageEventData The parameter string part of the URL.
*/
LayoutContainer.prototype.pageParametersChanged = function(pageEventData) {
var parameters = this.getParameterData(pageEventData.parameters);
$.Topic(PubSub.topicNames.PAGE_PARAMETERS).publishWith(
{
pageId: pageEventData.pageId,
seoslug: pageEventData.seoslug,
parameters: parameters
},[{message:"success"}]);
this.pageContextChanged(pageEventData);
};
/**
* Listens for PAGE_VIEW_CHANGED events and updates the
* layout according to the new view id.
*
* @private
* @function
* @name LayoutContainer#pageViewChanged
* @param {Object} pageEventData Arguments passed in via the page view event.
*/
LayoutContainer.prototype.pageViewChanged = function (pageEventData) {
var self = this;
self.currentPage = pageEventData;
// default location if no pageId is provided
var requestURL = 'home/';
var params = null;
if (pageEventData.pageId) {
// use the provided page ID
requestURL = pageEventData.pageId;
}
if (pageEventData.contextId) {
// If we have context params add them
requestURL = pageEventData.pageId;
params = {};
params[CCConstants.PAGE_PARAM] = pageEventData.contextId;
params[CCConstants.DATA_ONLY] = false;
}
this.load('layout', requestURL, params,
// Callback for load result
function (result) {
self.isPreview = result.isPreview();
var subscription;
// Update context variables
self.setContextData(result.data);
self.updatePageEventData(result.data, pageEventData);
if (result.data && result.data.global && result.data.global.site) {
if (result.data.global.site.tenantId) {
pageViewTracker.tenantId(result.data.global.site.tenantId);
}
}
// Send the parameters
if (pageEventData.parameters) {
var parameters = self.getParameterData(pageEventData.parameters);
$.Topic(PubSub.topicNames.PAGE_PARAMETERS).publishWith(
{
pageId: pageEventData.pageId,
seoslug: pageEventData.seoslug,
parameters: parameters
},[{message:"success"}]);
}
// Update page regions
// TODO: Fire event here rather than
// direct link to the view model
// masterViewModel.regions(result.regions());
$.Topic(PubSub.topicNames.PAGE_LAYOUT_LOADED).publish(result, pageEventData);
var param = {"pageId" : pageEventData.pageId};
self.storeServerLog.logInfo("getPage",self.storeServerLog.getMessage("getPage", param));
// if we have pending widgets, delay this event till they load
if (self.pendingWidgets().length === 0)
$.Topic(PubSub.topicNames.PAGE_READY).publish(pageEventData);
else {
// wait for pending widget count to drop to zero
subscription = self.pendingWidgets.subscribe(function(watchedPendingWidgets) {
if (watchedPendingWidgets.length === 0) {
$.Topic(PubSub.topicNames.PAGE_READY).publish(pageEventData);
subscription.dispose(); // stop listening
}
});
}
},
// Error Callback. Server is likely down.
self.handleServerError
);
};
/**
* Request to persist the creation of a new object.
*
* @private
* @function
* @name LayoutContainer#create
* @param {String} type The type of data being created.
* @param {String|String[]} id The id of the object being created using either a simple id (string) or
* complex id (an array of values).
* @param {Object} model The viewModel to persist the creation of.
* @param {Object} params Additional parameters used for the request.
* @param {function} success A success function callback. Passes paramters (value, caller). value is the result of the create,
* caller is used to reference the calling context.
* @param {function} error An error function callback invoked if there was an error with creation of the object.
* @param {Object} caller The caller to be passed to the success and error callbacks.
*/
LayoutContainer.prototype.create = function(type, id, model, params, success, error, caller) {
var self = this,
builder,
createFunc,
json;
if($.isFunction(params)) {
if($.isFunction(success)) {
caller = error;
error = success;
} else {
caller = success;
}
success = params;
params = null;
} else if(!$.isFunction(error)) {
caller = error;
error = null;
}
//Get the viewModelBuilder for this type of object. If no builder, we
//cannot load an object of this type.
builder = this.getViewModelBuilder(type);
if(!builder || !builder.create) {
return;
}
//Add the item to the cache if it is cachable
if(builder.cachable) {
var cacheKey = self.idAndParamsToCacheKey(id, params);
self.cache.set(type, cacheKey, model);
}
//Get the builder's load function into this context.
createFunc = builder.create;
if(!createFunc) {
throw "Loading of resource type: " + type + " forbidden";
}
if(createFunc === true) {
json = model;
} else {
json = createFunc(model, params, caller);
}
//Ask the adapter to save the json
this.adapter.persistCreate(type, id, json, params,
function(data) {
if(success) {
success(data, caller);
}
},
function(data) {
if(error) {
error(data, caller);
}
});
};
/**
* Request to persist an update of an object.
*
* @private
* @function
* @name LayoutContainer#update
* @param {string} type The type of data being updated.
* @param {string|string[]} id The id of the object being updated using either a simple id (string) or
* complex id (an array of values).
* @param {Object} model The viewModel to update.
* @param {Object} params Additional parameters used for the request.
* @param {function} success A success function callback. Passes paramters (value, caller). value is the result of the update,
* caller is used to reference the calling context.
* @param {function} error An error function callback invoked if there was an error with updating the data.
* @param {Object} caller The caller to be passed to the success and error callbacks.
*/
LayoutContainer.prototype.update = function(type, id, model, params, success, error, caller) {
var self = this,
builder,
updateFunc,
json,
errorCallback,
successCallback;
if($.isFunction(params)) {
if($.isFunction(success)) {
caller = error;
error = success;
} else {
caller = success;
}
success = params;
params = null;
} else if(!$.isFunction(error)) {
caller = error;
error = null;
}
//Get the viewModelBuilder for this type of object. If no builder, we
//cannot load an object of this type.
builder = this.getViewModelBuilder(type);
if(!builder || !builder.update) {
return;
}
//Get the builder's load function into this context.
updateFunc = builder.update;
if(!updateFunc) {
throw "Updating of resource type: " + type + " forbidden";
}
if(updateFunc === true) {
json = model;
} else {
json = updateFunc(model, params, caller);
}
//Ask the adapter to save the json
this.adapter.persistUpdate(type, id, json, params,
function(data) {
if(success) {
success(data, caller);
}
},
function(data) {
if(error) {
error(data, caller);
}
});
};
/**
* Request to permanently delete a new object.
*
* @private
* @function
* @name LayoutContainer#remove
* @param {string} type The type of data being deleted.
* @param {string|string[]} id The id of the object being deleted using either a simple id (string) or
* complex id (an array of values).
* @param {Object} params Additional parameters used for the request.
* @param {function} success A success function callback. Passes paramters (value, caller). value is the result of the deletion,
* caller is used to reference the calling context.
* @param {function} error An error function callback invoked if there was an error with deletion of the object.
* @param {Object} caller The caller to be passed to the success and error callbacks.
*/
LayoutContainer.prototype.remove = function(type, id, params, success, error, caller) {
var self = this,
builder,
removeFunc;
if($.isFunction(params)) {
if($.isFunction(success)) {
caller = error;
error = success;
} else {
caller = success;
}
success = params;
params = null;
} else if(!$.isFunction(error)) {
caller = error;
error = null;
}
//Get the viewModelBuilder for this type of object. If no builder, we
//cannot load an object of this type.
builder = this.getViewModelBuilder(type);
if(!builder || !builder.remove) {
return;
}
//If the object is cachable check the cache and result if there is a cache hit.
if(builder.cachable) {
var cacheKey = self.idAndParamsToCacheKey(id, params);
this.cache.set(type, cacheKey, null);
}
//Get the builder's load function into this context.
removeFunc = builder.remove;
if(!removeFunc) {
throw "Deleting of resource type: " + type + " forbidden";
}
//Ask the adapter to retreive the object.
this.adapter.persistDelete(type, id, params,
function(data) {
//Perform the callback
if(success) {
success(data, caller);
}
},
function(data) {
if(error) {
error(data, caller);
}
});
};
/**
* Request to load a piece of external data based on url, id and params.
*
* @public
* @function
* @name LayoutContainer#loadRequestForLayout
* @param {string} pUrl The Url of the endpoint.
* @param {Object} pData Additional parameters used for the request.
* @param {string|string[]} pParam1 The id of the object(s) being loaded using either a simple id (string) or
* complex id (an array of values).
*/
LayoutContainer.prototype.loadRequestForLayout = function(pUrl, pData, pParam1, pParam2, pParam3, pParam4, pBeforeSendCallback) {
var deferred = $.Deferred();
ccRestClient.request(pUrl, pData,
function (result) {
deferred.resolve(result);
},
function (result) {
deferred.reject(result);
if (result.status == CCConstants.HTTP_NOT_FOUND) {
// Passing in true for noHistory param (2nd param), we don't want the url to change on 404 pages.
navigation.goTo("/404", true, true);
}
}, pParam1, pParam2, pParam3, pParam4, pBeforeSendCallback);
return deferred;
};
/**
* Request to load page endpoint data. The data is loaded and converted
* to a view model before being passed to the success callback.
*
* @public
* @function
* @name LayoutContainer#loadDataForLayout
* @param {Object} input Additional parameters used for the request.
* @param {string|string[]} id The id of the object(s) being loaded using either a simple id (string) or
* complex id (an array of values).
* @param {function} success A success function callback. Passes paramters (viewModel, caller). viewModel is the result of the load,
* caller is used to reference the calling context.
* @param {function} error An error function callback invoked if there was an error with loading the data.
* @param {Object} builder The view model builder object fot type 'layout'
* @param {Object} caller The caller to be passed to the success and error callbacks.
*/
LayoutContainer.prototype.loadDataForLayout = function(input, id, success, error, builder, caller) {
var self = this, params = input, loadFunc = builder.load;
var vp = viewportHelper.viewportDesignation();
var layoutOnlyRequest = $.extend({}, input, {layoutOnly:true});
if (vp) {
layoutOnlyRequest['ccvp'] = vp;
}
$.when (
this.loadRequestForLayout(CCConstants.ENDPOINT_PAGES_GET_PAGE, layoutOnlyRequest, id),
this.loadRequestForLayout(CCConstants.ENDPOINT_PAGES_GET_PAGE, $.extend({}, input, {cacheableDataOnly:true}), id),
this.loadRequestForLayout(CCConstants.ENDPOINT_PAGES_GET_PAGE, $.extend({}, input, {currentDataOnly:true}), id)
).done (
function (pLayoutResult, pCacheableDataResult, pCurrentDataResult) {
if (success) {
// This will merge the 3 results into 1, meaning the response will look the same to the caller, regardless of the
// request being split into multiple calls.
var data = $.extend(true, pLayoutResult, pCacheableDataResult, pCurrentDataResult);
var result;
//Perform the load function to transform the JSON. If
//load is true, then just pass through the data. Otherwise
//set result to the transformed data.
if(loadFunc === true) {
result = data;
} else {
result = loadFunc(data, self, params);
}
//Add the item to the cache if it is cachable
if(builder.cachable) {
var cacheKey = self.idAndParamsToCacheKey(id, params);
self.cache.set(type, cacheKey, result);
}
//Perform the callback
success (result, caller);
} else if (result.status == 404) {
navigation.goTo("/404", true, true);
} else if (error && pResult) {
error(pResult, caller);
}
}
);
};
/**
* Request to load a piece of external data based on type, id, and params. The data is loaded and converted
* to a view model before being passed to the success callback.
*
* @public
* @function
* @name LayoutContainer#load
* @param {string} type The type of data being requested.
* @param {string|string[]} id The id of the object(s) being loaded using either a simple id (string) or
* complex id (an array of values).
* @param {Object} params Additional parameters used for the request.
* @param {function} success A success function callback. Passes paramters (viewModel, caller). viewModel is the result of the load,
* caller is used to reference the calling context.
* @param {function} error An error function callback invoked if there was an error with loading the data.
* @param {Object} caller The caller to be passed to the success and error callbacks.
*/
LayoutContainer.prototype.load = function(type, id, params, success, error, caller) {
var self = this,
builder,
loadFunc,
cacheResult;
if($.isFunction(params)) {
if($.isFunction(success)) {
caller = error;
error = success;
} else {
caller = success;
}
success = params;
params = null;
} else if(!$.isFunction(error)) {
caller = error;
error = null;
}
//Get the viewModelBuilder for this type of object. If no builder, we
//cannot load an object of this type.
builder = this.getViewModelBuilder(type);
// If it was not in the cache, need to
// call the load function
if(!builder || !builder.load) {
return;
}
//If the object is cachable check the cache and result if there is a cache hit.
if(builder.cachable) {
var cacheKey = self.idAndParamsToCacheKey(id, params);
cacheResult = this.cache.get(type, cacheKey);
if(cacheResult.hit === true) {
if(success) {
success(cacheResult.result, caller);
}
return;
}
}
//Get the builder's load function into this context.
loadFunc = builder.load;
if(!loadFunc) {
throw "Loading of resource type: " + type + " forbidden";
}
var input = params ? params : {}
if (type == 'layout' && !input.dataOnly) {
this.loadDataForLayout(input, id, success, error, builder, caller)
} else {
//Ask the adapter to retreive the object.
this.adapter.loadJSON(type, id, params,
//success callback
function(data) {
var result;
//Perform the load function to transform the JSON. If
//load is true, then just pass through the data. Otherwise
//set result to the transformed data.
if(loadFunc === true) {
result = data;
} else {
result = loadFunc(data, self, params);
}
//Add the item to the cache if it is cachable
if(builder.cachable) {
var cacheKey = self.idAndParamsToCacheKey(id, params);
self.cache.set(type, cacheKey, result);
}
//Perform the callback
if(success) {
success(result, caller);
}
},
//error callback
function(data) {
if(error) {
error(data, caller);
}
});
}
};
/**
* Build a view model from the provided json for the given
* item type then sets that item as the current item for the given type.
* If the item is cachable and an id is provided the cache will be updated.
*
* @private
* @function
* @name LayoutContainer#loadCurrentFromJSON
* @param {String} type The type of item to load and set as current.
* @param {Object} json The json object to transform into a view model
* @param {Object} params Additional parameters for the load.
* @param {string|string[]} id The id for the item as either a simple string id
* or complex array id. Required to cache the viewModel. The viewModel
* won't be cached if omitted
*/
LayoutContainer.prototype.loadCurrentFromJSON = function(type, json, params, id) {
var scope, builder, viewModel, cacheResult;
builder = this.getViewModelBuilder(type);
if(!builder) {
return null;
}
if(builder.scope) {
scope = builder.scope;
} else {
scope = 'page';
}
if(builder.load) {
if(builder.load === true) {
this.contextHandler.set(type, json, scope);
if(id && builder.cachable) {
var cacheKey = self.idAndParamsToCacheKey(id, params);
this.cache.set(type, cacheKey, viewModel);
}
return json;
}
viewModel = builder.load(json, this, params);
this.contextHandler.set(type, viewModel, scope);
if(id && builder.cachable) {
var cacheKey = self.idAndParamsToCacheKey(id, params);
this.cache.set(type, cacheKey, viewModel);
}
return viewModel;
}
return null;
};
/**
* Instantiate a widget from a definition. Effectively copies all properties from
* the passed widget to a new {@link WidgetViewModel} then initializes the widget. The returned
* widget is a new WidgetViewModel with all of the same properties & values as the old
* widget, but with distinct observables.
*
* @private
* @function
* @name LayoutContainer#instantiateWidget
* @param {WidgetViewModel} widget The widget definition to instantiate.
* @returns {WidgetViewModel} The instantiated widget.
* @see LayoutContainer#initializeWidget
*/
LayoutContainer.prototype.instantiateWidget = function (widget) {
var newWidget = new this.WidgetViewModel(this.basePath),
key,
ii;
//Copy all properties from the widget definition to the widget instance
for(key in widget) {
if(widget.hasOwnProperty(key)) {
//If copying an observable, create a new observable.
if(ko.isObservable(widget[key]) && !ko.isComputed(widget[key])) {
//If remove exists the observable is an array
if(widget[key].remove) {
newWidget[key] = ko.observableArray(widget[key]());
} else {
newWidget[key] = ko.observable(widget[key]());
}
} else if(!ko.isComputed(widget[key])){
//If not an observable just copy the value
newWidget[key] = widget[key];
}
}
}
//Initialize the new widget
this.initializeWidget(newWidget, true);
return newWidget;
};
/**
* Run Widget Initialization after context data has been set from server.
*
* @private
* @function
* @name LayoutContainer#initializeWidget
* @param {WidgetViewModel} widget Widget to initialize
* @param {boolean} load=false Whether to run 'onLoad' function and resolve special properties.
* @param {function} javascriptLoadedCallback Function/script to run after initializing widget.
*/
LayoutContainer.prototype.initializeWidget = function (widget, load, javascriptLoadedCallback) {
var self = this;
self.contextDataSetSubscriber.done(function(){
self.runWidgetInitialization(widget, load, javascriptLoadedCallback);
});
};
/**
* Initializes the widget by loading its custom javascript, resolving any special properties,
* and running the onLoad function. Marks the widget as initialized once the processing has completed.
*
* @private
* @function
* @name LayoutContainer#runWidgetInitialization
* @param {WidgetViewModel} widget The widget to initialize
* @param {boolean} load Whether or not to run the onLoad function and resolve its
* special properties. True will cause the onLoad function to run, default is false.
* @param {function} javascriptLoadedCallback Function/script to run after initializing widget.
*/
LayoutContainer.prototype.runWidgetInitialization = function (widget, load, javascriptLoadedCallback) {
var importKey, imports, scope, ii, layoutContainer = this;
layoutContainer.pendingWidgets.push(widget);
if(load) {
//Load any things pointed to as part of 'current'
if(widget.imports) {
imports = ko.utils.unwrapObservable(widget.imports);
for(ii = imports.length - 1; ii >= 0; ii -= 1) {
importKey = imports[ii];
scope = this.getViewModelBuilder(importKey);
if(scope) {
scope = scope.scope || 'page';
}
widget[importKey] = this.contextHandler.get(importKey, scope);
}
}
}
//If the widget has javascript load it.
if(ko.utils.unwrapObservable(widget.javascript)) {
// Use require to load the javascript.
// Check asset mappings to make sure we are loading
// the correct version
var mappingBase = widget.jsPath() + '/';
var jsPath = widget.javascript();
if (widget.assetMappings) {
var mappingKey = '/js/' + widget.javascript() + '.js';
var mappingValue = widget.assetMappings[mappingKey];
if (mappingValue) {
var idx = mappingValue().lastIndexOf('/');
mappingBase = mappingValue().substring(0,idx);
jsPath = mappingValue();
}
}
// While loading the module thru require([],fn{}), require creates a module
//map with the url to load the module from, dependencies, and call back after
//loading the module. During the migration from require 2.0.6 to require.js 2.1.10,
//it is observed that there is a delay of the 4 milliseconds added by require to load
//the dependencies as part of context.nextTick.and prepare the module map after
//that delay. This was creating the problem while loading the widgets as the delay
//overrides the base url for all the widgets. So we have to override the nextTick
//implementation to execute load immediately.
requirejs.s.contexts._.nextTick = function(fn){fn();}
var mapping = requirejs.s.contexts._.config.map ? requirejs.s.contexts._.config.map : {};
mapping[jsPath] = {};
// For widgets that contain multiple js files, we need to provide a mapping so that require knows to load it from the url specified in asset mappings
for (var asset in widget.assetMappings) {
// Just map js files that aren't the main widget js file
if (asset.indexOf('/js/') === 0 && asset.indexOf(widget.javascript() + '.js') === -1) {
var extPos = asset.indexOf('.js');
var url = widget.assetMappings[asset]();
var moduleName = asset.substring(1, extPos);
mapping[jsPath][moduleName] = url;
}
}
require({baseUrl: mappingBase, map : mapping}, [jsPath], function(extensions) {
if(typeof extensions === 'function') {
extensions = extensions().bind(ko);
}
var key;
//For each property in the returned object copy it to the widget.
for(key in extensions) {