-
Notifications
You must be signed in to change notification settings - Fork 1
/
Factory.js
executable file
·1094 lines (759 loc) · 36.8 KB
/
Factory.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
import { EventBus } from "./EventBus.js";
// Create global namespaces for modules
export var ComponentConfigs = {}; // aka componentConfig
export var ComponentProps = {};
// Builder
export var Factory = (function( EventBus ) {
var componentStore = {};
// Module Features
var builder = function( componentConfig = {}, inlineTemplateNode ) {
var debug = (componentConfig.debug) ? componentConfig.debug : false;
// Public Methods
var _public = {
get : {},
commit : {},
dispatch : {},
hooks : {
beforeCreate : function( state ) { if(!debug) {return}; console.info( '1. This will not run unless defined during component registration', state ); },
beforeUpdate : function( delta ) { if(!debug) {return}; console.log( '2. Module will update: ' + this.component().get.state( 'key' ), delta ); },
onUpdate : function( delta ) { if(!debug) {return}; console.log( '3. Module updating: ' + this.component().get.state( 'key' ), delta ); },
afterUpdate : function( delta ) { if(!debug) {return}; console.log( '4. Module updated: ' + this.component().get.state( 'key' ), delta ); },
afterCreate : function( state ) { if(!debug) {return}; console.log( '5. Module was created: ' + state.key ) },
beforeMount : function( state ) { if(!debug) {return}; console.log( '6. Module will mount: ' + state.key ); },
onMount : function( state ) { if(!debug) {return}; console.log( '7. Module mounting: ' + state.key ); },
afterMount : function( state ) { if(!debug) {return}; console.log( '8. Module has mounted: ' + state.key ); }
}
};
// Private
var component = {
ref : '',
props : {},
state : {
key : '', // Placeholder; created dynamically at the time the component is instantiated
componentName : '', // Placeholder; this the common name of the component determined by the developer manually, is not unique
eventBus : [], // Placeholder; this is updated when the the component is registered to eventBus
eventListeners : {},
firstRenderFlag : true
},
inlineTemplateNode : inlineTemplateNode,
template : (componentConfig.template) ? componentConfig.template : null
};
var _private = {};
/**
* Update eventBus, notifies eventBus(s) that a change has occured within a given component
*/
_private.notifyEventBus = function( notifierKey = '', notifierStateDelta = {} ) {
const eventBus = _public.get.state( 'eventBus' );
for( let i = 0; i < eventBus.length; i++ ) {
EventBus.getBus( eventBus[ i ] ).dispatch(
'notifyBus',
{
'notifierType' : 'component',
'notifierKey' : notifierKey,
'notifierStateDelta' : notifierStateDelta
}
);
}
}
_private.hasStateChanged = function( newState ) {
const currentState = _public.get.state();
let comparison = {};
let intentionalChange = false; // True if any value within comparison.diff !== null
comparison.stateChanged = false;
comparison.diff = _private.compareObjects( currentState, newState );
for( let key in comparison.diff ) {
// Handling Unintentional Changes in State changes
//
// Evaluate the comparison.diff for values other than null.
// If the current state has key-value pairs that the new state
// does not then the comparison.diff will contain the key
// with a value of null. This counts as true change however,
// we are going to interpret null as an unintentional change in state.
//
// In order for a developer to commit an intentional change where
// the new state of includes a key-value pair with value = null,
// then consider removing the key from the currentState or setting the
// value of currentState at the given key-value pair to an undefined,
// empty string, zero, negative one or false.
if( comparison.diff[ key ] === null ) {
continue;
} else {
intentionalChange = true;
break; // if even one field has intentionally changed then exit loop
}
}
if( Object.keys( comparison.diff ).length > 0 && intentionalChange === true ) {
comparison.stateChanged = true;
}
return comparison;
}
/* Getters */
_public.get.state = function( fieldName = '' ) {
return ( fieldName == '' ) ? component.state : component.state[ fieldName ];
}
_public.get.props = function( fieldName = '' ) {
return ( fieldName == '' ) ? component.props : component.props[ fieldName ];
}
_public.get.ref = function() {
return component.ref;
}
_public.get.observers = function( observerName = '' ) {
if( observerName !== '' ) {
observerIndex = component.observers.indexOf( observerName );
observer = component.observers[ observerIndex ];
}
return ( observerName == '' ) ? component.observers : observer;
}
_public.get.inlineTemplateNode = function() {
let node = null;
node = ( component.inlineTemplateNode === null ) ? _public.dispatch.createTemplateNode() : component.inlineTemplateNode;
if( node === null ) {
console.error( 'Inline template does not exist' );
}
return node;
}
_public.get.templateString = function() {
return component.template;
}
/* Mutations */
_public.commit.state = function( newState = {}, triggerRender = true, triggerNotification = true ) {
// 1) If state is different then update
const differencesInState = _private.hasStateChanged( newState ); // Returns object
if( differencesInState.stateChanged === true ) {
// 2) Update current state object with only the things that changed
for( let key in differencesInState.diff ) {
// Skip so that we don't overwrite values in current state with null
if( differencesInState.diff[ key ] === null ) continue;
component.state[ key ] = differencesInState.diff[ key ];
}
if (debug) { console.log( 'Change in state: ', newState ) };
// 3) Re-render existing node
if( !triggerRender ) return;
_public.dispatch.render( newState );
// 4) Notify observers
if( !triggerNotification ) return;
_private.notifyEventBus( _public.get.state ('key' ), newState );
}
}
_public.commit.props = function( newProps = {} ) {
for( let key in newProps ) {
component.props[ key ] = newProps[ key ];
}
}
_public.commit.ref = function( newRef = '' ) {
component.ref = newRef;
}
/* Actions */
_public.dispatch.update = function( notifierKey, notifierStateDelta ) {
// This is a response to an EventBus Notification
// Developers are responsible for defining this method
}
_public.dispatch.notifyEventBus = function( notifierKey, notifierStateDelta ) {
_private.notifyEventBus( notifierKey, notifierStateDelta );
}
_public.dispatch.insertTemplate = function( selector, insertType = 'append' ) {
let templateNode = _public.get.inlineTemplateNode();
if(templateNode) {
let documentNode = document.querySelector( selector );
if(insertType === 'append') {
documentNode.appendChild( templateNode );
} else {
documentNode.prependChild( templateNode );
}
}
},
_public.dispatch.mount = function() {
// 1) Hook beforeMount - compile template
_public.hooks.beforeMount( _public.get.state() );
// 2) Hook onMount - add template to DOM
_public.hooks.onMount( _public.get.state() );
// 3) Hook afterMount - post processing
_public.hooks.afterMount( _public.get.state() );
component.state.firstRenderFlag = false;
// 4) Notify the rest of the eventBus
_public.dispatch.notifyEventBus( _public.get.state( 'key' ), _public.get.state() );
}
_public.dispatch.render = function( delta = {} ) {
// 1) Hook beforeUpdate- compile template
_public.hooks.beforeUpdate( delta );
// 2) Hook onUpdate - add template to DOM
_public.hooks.onUpdate( delta );
// 3) Hook afterUpdate - post processing
_public.hooks.afterUpdate( delta );
}
_public.dispatch.registerInstance = function( componentConfig = {} ) {
// Update Gets
if(
componentConfig.get !== undefined &&
componentConfig.get !== null &&
typeof( componentConfig.get ) !== "object"
) {
const getKeys = Object.keys( componentConfig.get );
for( let i = 0; i < getKeys.length; i++ ) {
_public.get[ getKeys[ i ] ] = componentConfig.get[ getKeys[ i ] ];
}
}
// Update Commits (Changes in state)
if(
componentConfig.commit !== undefined &&
componentConfig.commit !== null &&
typeof( componentConfig.commit ) === "object"
) {
const commitKeys = Object.keys( componentConfig.commit );
for( let i = 0; i < commitKeys.length; i++ ) {
_public.commit[ commitKeys[ i ] ] = componentConfig.commit[ commitKeys[ i ] ];
}
}
// Update dispatches (Actions)
if(
componentConfig.dispatch !== undefined &&
componentConfig.dispatch !== null &&
typeof( componentConfig.dispatch ) === "object"
) {
const dispatchKeys = Object.keys( componentConfig.dispatch );
for( let i = 0; i < dispatchKeys.length; i++ ) {
_public.dispatch[ dispatchKeys[ i ] ] = componentConfig.dispatch[ dispatchKeys[ i ] ];
}
}
// Update Hooks (Intrinsic/Custom)
if(
componentConfig.hooks !== undefined &&
componentConfig.hooks !== null &&
typeof( componentConfig.hooks ) === "object"
) {
var hookKeys = Object.keys( componentConfig.hooks );
var keyToUse = ''; // Used to identify/select _public key
for( let i = 0; i < hookKeys.length; i++ ) {
switch( hookKeys[ i ] ) {
case 'beforeCreate' :
keyToUse = 'beforeCreate';
break;
case 'created' :
keyToUse = 'created';
break;
case 'beforeMount' :
keyToUse = 'beforeMount';
break;
case 'onMount' :
keyToUse = 'onMount';
break;
case 'afterMount' :
keyToUse = 'afterMount';
break;
case 'beforeUpdate' :
keyToUse = 'beforeUpdate';
break;
case 'onUpdate' :
keyToUse = 'onUpdate';
break;
case 'afterUpdate' :
keyToUse = 'afterUpdate';
break;
default :
keyToUse = hookKeys[ i ];
break;
}
// Replace the 'create', 'beforeMount', 'onMount', and 'afterMount' functions
// with the incoming method specified by the developer OR add a custom hook
// specified by the developer
_public.hooks[ keyToUse ] = componentConfig.hooks[ hookKeys[ i ] ];
}
}
let triggerRender = false; // Waiting to mount check
// Update the component's internal component object
_public.commit.ref( componentConfig.ref );
_public.commit.props( componentConfig.props );
_public.commit.state( componentConfig.state, triggerRender );
componentConfig.ref = null; //clean up
return _public;
}
_public.dispatch.createInlineTemplate = function( template, componentKey ) {
var inlineTemplateNode = Factory.templateToHTML( template );
inlineTemplateNode.setAttribute( 'data-key', componentKey );
component.inlineTemplateNode = inlineTemplateNode;
return _public.get.inlineTemplateNode();
}
// Alias for createInlineTemplate()
_public.dispatch.createNodeFromTemplate = function( template, componentKey ) {
return _public.dispatch.createInlineTemplate( template, componentKey );
}
_public.dispatch.createTemplateNode = function() {
var inlineTemplateNode = Factory.templateToHTML( component.template );
try {
inlineTemplateNode.setAttribute( 'data-key', _public.get.state( 'key' ) );
} catch (error) {
console.error('Template does not exist');
return false;
}
component.inlineTemplateNode = inlineTemplateNode;
return _public.get.inlineTemplateNode();
}
// Grant access to all _public methods within each of the children of the _public class
_public.get.component = function() {
return {
commit : _public.commit,
dispatch : _public.dispatch,
hooks : _public.hooks
};
};
_public.dispatch.component = function() {
return {
get : _public.get,
commit : _public.commit,
hooks : _public.hooks
};
};
_public.commit.component = function() {
return {
get : _public.get,
dispatch : _public.dispatch,
hooks : _public.hooks
};
};
_public.hooks.component = function() {
return {
get : _public.get,
commit : _public.commit,
dispatch : _public.dispatch,
hooks : _public.hooks
};
};
/*!
* Find the differences between two objects and push to a new object
* (c) 2019 Chris Ferdinandi & Jascha Brinkmann, MIT License, https://gomakethings.com & https://twitter.com/jaschaio
* @param {Object} currentState The original object
* @param {Object} newState The object to compare against it
* @return {Object} An object of differences between the two
*/
_private.compareObjects = function( currentState = {}, newState = {} ) {
// Make sure an object to compare is provided
if (!newState || Object.prototype.toString.call(newState) !== '[object Object]') {
return currentState;
}
//
// Variables
//
var diffs = {};
var key;
//
// Methods
//
/**
* Check if two arrays are equal
* @param {Array} arr1 The first array
* @param {Array} arr2 The second array
* @return {Boolean} If true, both arrays are equal
*/
const arraysMatch = function (arr1, arr2) {
// Check if the arrays are the same length
if (arr1.length !== arr2.length) return false;
// Check if all items exist and are in the same order
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) return false;
}
// Otherwise, return true
return true;
};
/**
* Compare two items and push non-matches to object
* @param {*} item1 The first item
* @param {*} item2 The second item
* @param {String} key The key in our object
*/
const compare = function (item1, item2, key) {
// Get the object type
let type1 = Object.prototype.toString.call(item1);
let type2 = Object.prototype.toString.call(item2);
// If type2 is undefined it has been removed
if (type2 === '[object Undefined]') {
diffs[key] = null;
return;
}
// If items are different types
if (type1 !== type2) {
diffs[key] = item2;
return;
}
// If an object, compare recursively
if (type1 === '[object Object]') {
let objDiff = _private.compareObjects(item1, item2);
if (Object.keys(objDiff).length > 1) {
diffs[key] = objDiff;
}
return;
}
// If an array, compare
if (type1 === '[object Array]') {
if (!arraysMatch(item1, item2)) {
diffs[key] = item2;
}
return; }
// Else if it's a function, convert to a string and compare
// Otherwise, just compare
if ( type1 === '[object Function]' ) {
if ( item1.toString() !== item2.toString() ) {
diffs[ key ] = item2;
}
} else {
if ( item1 !== item2 ) {
diffs[ key ] = item2;
}
}
};
//
// Compare our objects
//
// Loop through the first object
for (key in currentState) {
if (currentState.hasOwnProperty(key)) {
compare(currentState[key], newState[key], key);
}
}
// Loop through the second object and find missing items
for (key in newState) {
if (newState.hasOwnProperty(key)) {
if (!currentState[key] && currentState[key] !== newState[key] ) {
diffs[key] = newState[key];
}
}
}
// Return the object of differences
return diffs;
}
// This runs immediately when the constructor is called
_public.dispatch.registerInstance( componentConfig );
// This binds the _public to the component exposing them for consumption publically
return (function(){
return _public;
})();
};
// Plugin Features
var ensureUniqueKey = function( newKey, existingKeys, componentName ) {
let needNewKey = false;
// TODO: Create a hash table of component instances
for( let i = 0; i < existingKeys.length; i++ ) {
if( newKey === existingKeys[ i ] ) {
needNewKey = true;
break;
}
}
return ( needNewKey ) ? ensureUniqueKey( returnRandomKey( componentName ), existingKeys, componentName ) : newKey;
}
var returnRandomKey = function( componentName ) {
return 'component_' + componentName + '_' + Math.floor(Math.random() * Math.floor(100000));
}
var registerComponent = function( componentConfig, manualRegistration = false ) {
let state = componentConfig.state;
let newModuleKey = '';
let componentsCreated = {}; // More than one component can be created at this time because of inline templating
if( state.componentName === undefined || state.componentName === null ) {
console.warn( 'EventBus: component instance not registered; state.componentName not specified' );
return false;
}
// If Inline Templates are detected then each item becomes a sub component of the parent component
// If there are inline templates then create an instance of the component with that inline template
// Otherwise the component will be created as an standalone instance of the component
let inlineTemplateSelector = '[data-inline-template="' + componentConfig.state.componentName + '"]';
let inlineTemplateNodeList = document.querySelectorAll( inlineTemplateSelector );
if( inlineTemplateNodeList.length > 0 ) {
for( let i = 0; i < inlineTemplateNodeList.length; i++ ) {
// Make sure that we are not we are not duplicating component registration
// TODO: Detect subcomponents
let existingModuleInstance = Factory.getComponentByKey( inlineTemplateNodeList[ i ].getAttribute( 'data-key' ) );
if( !existingModuleInstance ) {
if( inlineTemplateNodeList[ i ].getAttribute( 'data-ref' ) !== null ) {
componentConfig.ref = inlineTemplateNodeList[ i ].getAttribute( 'data-ref' );
}
newModuleKey = instantiateComponent( componentConfig, inlineTemplateNodeList[ i ] );
// add data-key attribute to prevent a dupe component instance the next time a new
inlineTemplateNodeList[ i ].setAttribute( 'data-key', newModuleKey );
componentsCreated[ newModuleKey ] = getComponentByKey( newModuleKey );
// Custom tasks performed after component has been created and reactivity has been established.
// Otherwise, standard routines will be performed which including notifications to related
// eventBuses that the state of a component has been updated, and the component itself will render
componentsCreated[ newModuleKey ].dispatch.mount();
// Set Event Listeners
setEventListeners( componentConfig );
}
}
} else {
if( !manualRegistration ) {
// Register without an inline template
newModuleKey = instantiateComponent( componentConfig );
componentsCreated[ newModuleKey ] = getComponentByKey( newModuleKey );
componentsCreated[ newModuleKey ].dispatch.mount();
// Set Event Listeners
setEventListeners( componentConfig );
}
}
if( manualRegistration ) {
newModuleKey = instantiateComponent( componentConfig );
componentsCreated[ newModuleKey ] = getComponentByKey( newModuleKey );
componentsCreated[ newModuleKey ].dispatch.mount();
}
// Return component
return componentsCreated;
}
const setEventListeners = function( componentConfig ) {
// Add Eventlisteners (Eventlisteners are added to the Window as named functions)
if(
componentConfig.props !== undefined &&
componentConfig.props.eventListeners !== undefined &&
componentConfig.props.eventListeners !== null &&
typeof( componentConfig.props.eventListeners ) === "object"
) {
let eventConfigs = componentConfig.props.eventListeners;
let configKeys = Object.keys( eventConfigs );
let componentKey = componentConfig.state.key;
let component = getComponentByKey( componentKey );
for(let i = 0; i < configKeys.length; i++) {
let eventConfig = eventConfigs[ configKeys[i] ];
let node = component.get.inlineTemplateNode();
if (node === null) return false;
if( eventConfig.selector === 'self' || eventConfig.selector === '' || eventConfig.selector === undefined ) {
try {
node.addEventListener( eventConfig.listener, (e) => {
eventConfig.callback(e, component, componentKey )
});
} catch( error ) {
console.error( "Not a valid event listener: " + eventConfig.listener )
}
} else {
try {
node.querySelector(eventConfig.selector).addEventListener( eventConfig.listener, (e) => {
eventConfig.callback(e, component, componentKey )
});
} catch( error ) {
console.error( error );
}
}
}
let triggerRender = false;
component.commit.state( { eventListenersExist : true }, triggerRender );
}
}
const instantiateComponent = function( componentConfig, inlineTemplateNode = null ) {
// Be sure not to re-register nodes that have already been registered
const allModules = Factory.getAllComponents();
const componentState = componentConfig.state;
let componentKey = '';
let beforeCreateExists = false;
// Determine whether user has defined custom
if(
componentConfig.hooks !== undefined &&
componentConfig.hooks !== null &&
typeof( componentConfig.hooks ) === "object"
) {
if(
componentConfig.hooks.beforeCreate !== undefined &&
componentConfig.hooks.beforeCreate !== null &&
typeof( componentConfig.hooks.beforeCreate ) === "function"
) {
beforeCreateExists = true;
}
}
// Validate Module ID is unique
if( componentState.key === undefined ) {
componentKey = ensureUniqueKey( returnRandomKey( componentState.componentName ), Object.keys( allModules ), componentState.componentName );
} else {
componentKey = ensureUniqueKey( componentState.key, Object.keys( allModules ), componentState.componentName );
}
// Update ID within state to ensure that the state is consistent with valid value
componentConfig.state.key = componentKey;
if( beforeCreateExists ) {
// Perform tasks before component has been created
componentConfig.hooks.beforeCreate( componentConfig.state, inlineTemplateNode );
}
// Store component in Factory
storeComponent(
componentKey,
new Factory.construct( componentConfig, inlineTemplateNode )
);
// Register component with parent eventBuses
if(
componentConfig.eventBus !== undefined &&
componentConfig.eventBus !== null &&
typeof( componentConfig.eventBus ) === "object"
) {
setParentBus( componentKey, componentConfig );
}
// Register components that this component should react to
if(
componentConfig.subscriptions !== undefined &&
componentConfig.subscriptions !== null &&
typeof( componentConfig.subscriptions ) === "object"
) {
setEventSubscriptions( componentKey, componentConfig );
} else {
// Check to see if parentEventBuss have been specified
if(
componentConfig.eventBus !== undefined &&
componentConfig.eventBus !== null &&
typeof( componentConfig.eventBus ) === "object"
) {
for( let i = 0; i < componentConfig.eventBus.length; i++ ) {
subscribeToAllEventNotifications( componentKey, componentConfig.eventBus[ i ] );
}
}
}
// Custom tasks performed after component has been created and reactivity has been established.
// Otherwise, standard routines will be performed which including notifications to related
// eventBuses that the state of a component has been updated, and the component itself will render
const newComponent = getComponentByKey( componentKey );
newComponent.hooks.afterCreate( newComponent.get.state() );
return componentKey;
}
const setParentBus = function( componentKey, componentConfig ) {
for( let i = 0; i < componentConfig.eventBus.length; i++ ) {
let eventBus = EventBus.getBus( componentConfig.eventBus[ i ] );
// Register component to given eventBuses
eventBus.dispatch(
'registerComponent', {
'key' : componentKey,
'componentObj' : getComponentByKey( componentKey )
});
}
}
const storeComponent = function( instanceKey, instanceObj ) {
componentStore[ instanceKey ] = instanceObj;
}
const getComponentByKey = function( nameOfInstance = '' ) {
return ( nameOfInstance !== '' && nameOfInstance !== null && nameOfInstance !== undefined ) ? componentStore[ nameOfInstance ] : false;
}
const getAllComponents = function() {
return componentStore;
}
const getComponentsByName = function( componentName = '' ) {
const componentKeys = Object.keys( getAllComponents() );
let componentsByModuleName = {};
for( let i = 0; i < componentKeys.length; i++ ) {
let currentModule = getComponentByKey( componentKeys[ i ] );
if( currentModule.get.state( 'componentName' ) === componentName ) {
componentsByModuleName[ componentKeys[ i ] ] = currentModule;
}
}
return componentsByModuleName;
}
const getComponentByName = function( $name = '' ) {
let componentList = Factory.getComponentsByName( $name );
let componentKeys = Object.keys( componentList );
return componentList[ componentKeys[ 0 ] ];
}
const setEventSubscriptions = function( subscriberKey = '', subscriptionPlan = {} ) {
const eventBusKeys = Object.keys( subscriptionPlan.subscriptions );
for( let x = 0; x < eventBusKeys.length; x++ ) {
// Ensure that the component is registered with the eventBus first
const subscriptionApp = EventBus.getBus( eventBusKeys[ x ] );
// Ensure that that the component that is subscribing to the eventBus
// is registered to the eventBus first
if( !subscriptionApp.get( 'getComponent', { 'componentKey' : subscriberKey } ) ) {
Factory.setParentBus( subscriberKey, {
eventBus : [ eventBusKeys[ x ] ]
});
}
}
/**
* Subscribe component to the given observable components
*/
for( let i = 0; i < eventBusKeys.length; i++ ) {
const eventBus = EventBus.getBus( eventBusKeys[ i ] );
const publisherKeys = subscriptionPlan.subscriptions[ eventBusKeys[ i ] ];
for( let j = 0; j < publisherKeys.length; j++ ) {
// Subscribe observers
eventBus.dispatch(
'addSubscribers', {
publisherKey : publisherKeys[ j ],
subscriberKey : subscriberKey
});
// Subscribe to observers
eventBus.dispatch(
'addSubscribers', {
publisherKey : subscriberKey,
subscriberKey : publisherKeys[ j ]
});
}
}
}
const subscribeToAllEventNotifications = function( componentKey, eventBusId ) {
if( eventBusId === undefined ) {
console.warn( 'Factory Plugin, subscribeToAllEventNotifications: eventBusId is undefined. Subscriptions failed.' );
return false;
}
// Find all components subscribed to the given eventBus
const subscriptionApp = EventBus.getBus( eventBusId );
if( subscriptionApp !== undefined && subscriptionApp.hasOwnProperty( 'get' ) ) {