forked from casperin/nod
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nod.js
1194 lines (930 loc) · 34.2 KB
/
nod.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
/**
*
*
* nod v.2.0.6
* Gorm Casper
*
*
*
* This is a short breakdown of the code to help you find your way around.
*
*
* An `element` always refer to some input element defined by the user via the
* `selector` key.
*
* A `metric` is the user created objects that is used to add checks to
* nod.
*
* Each `element` will have at most one of a `listener`, a `checker`, a
* `checkHandler`, and a `domNode` "attached" to it. The `listener` listens
* for inputs or changes to the `element` and passes the new value on to to the
* `checker` which performs its checks and passes the the results on to the
* `checkHandler` which calculates the new state of the `element` which it
* passes on to the `domNode` which will update the dom.
*
* The four main parts, the listener, the checker, the checkHandler, and the
* domNode all communicate through the `mediator` by firing events identified
* by a unique id. They do not know of each other's existance, and so no
* communication flows directly between them.
*
* All listeners, checkers, handlers, and domNodes are grouped together in
* `collections`, which are basically a glorified array that makes it easy
* not to get duplicate items for each element (for instance two listeners
* listening to the same element).
*
* The communication flow looks like this:
* listener -> checker -> checkHandler -> domNode
*
* Between each part, you have the mediator.
*
*
* `Metrics` are added by the user, which sets up the system above. Notice
* that a metric can target multiple elements at once, and that there can
* be overlaps. One metric definitely does not equal one element or one
* check.
*
*/
function nod (config) {
var form,
configuration = {},
mediator = nod.makeMediator(),
eventEmitter = nod.makeEventEmitter(mediator),
// Creating (empty) collections
listeners = nod.makeCollection(nod.makeListener),
checkers = nod.makeCollection(nod.makeChecker),
checkHandlers = nod.makeCollection(nod.makeCheckHandler),
domNodes = nod.makeCollection(nod.makeDomNode);
/**
* Entry point for the user. The user passes in an array of metrics (an
* object containing a selector, a validate string/function, etc.) and it
* gets processed from here.
*
* This function, is mostly about cleaning up what the user passed us.
*/
function addMetrics (metrics) {
// Make sure we are dealing with an array of metrics.
var arrayMetrics = Array.isArray(metrics) ? metrics : [metrics];
arrayMetrics.forEach(function (metric) {
var validateArray, errorMessageArray;
// If the 'validate' is not an array, then we're good to go.
if (!Array.isArray(metric.validate)) {
addMetric(metric);
// If it is an array (e.g., validate: ['email', 'max-length:10']),
// then we need to split them up into multiple metrics, and add
// them individually.
} else {
if (!Array.isArray(metric.errorMessage)) {
throw 'If you pass in `validate:...` as an array, then `errorMessage:...` also needs to be an array. "' + metric.validate + '", and "' + metric.errorMessage + '"';
}
// We store each as arrays, and then run through them,
// overwriting each of the keys accordingly.
validateArray = metric.validate;
errorMessageArray = metric.errorMessage;
validateArray.forEach(function (validate, i) {
// Overwrite the array with the individual 'validate' and
// 'errorMessage'.
metric.validate = validate;
metric.errorMessage = errorMessageArray[i];
addMetric(metric);
});
}
});
}
function addMetric (metric) {
var specialTriggers = [],
// The function that will check the value of the element.
checkFunction = nod.getCheckFunction(metric),
// A list of elements that this metric will target.
elements = nod.getElements(metric.selector),
// A "set" here, refers to an obj with one listener, one checker,
// and one checkHandler. Only every one for each element in the
// dom.
metricSets = elements.map(function (element) {
return {
listener: listeners.findOrMake(element, mediator, metric.triggerEvents, configuration),
checker: checkers.findOrMake(element, mediator),
checkHandler: checkHandlers.findOrMake(element, mediator, configuration),
domNode: domNodes.findOrMake(element, mediator, configuration)
};
});
// Saved for later reference in case the user has a `tap` function
// defined.
checkFunction.validate = (typeof metric.validate === 'function') ? metric.validate.toString() : metric.validate;
// Special cases. These `validates` affect each other, and their state
// needs to update each time either of the elements' values change.
if (metric.validate === 'one-of' || metric.validate === 'only-one-of' || metric.validate === 'some-radio') {
specialTriggers.push(metric.selector);
}
if (typeof metric.validate === 'string' && metric.validate.indexOf('same-as') > -1) {
specialTriggers.push(metric.validate.split(':')[1]);
}
// Helper function, used in the loop below.
function subscribeToTriggers (checker, selector) {
var triggerElements = nod.getElements(selector);
triggerElements.forEach(function (element) {
var listener = listeners.findOrMake(element, mediator, null, configuration);
checker.subscribeTo(listener.id);
});
}
// Here we set up the "connections" between each of our main parts.
// They communicate only through the mediator.
metricSets.forEach(function (metricSet) {
// :: Listener -> Checker
// We want our checker to listen to the listener. A listener has an
// id, which it uses when it fires events to the mediator (which
// was set up when the listener was created).
metricSet.checker.subscribeTo(metricSet.listener.id);
// If the user set a `triggeredBy`, the checker need to listen to
// changes on this element as well.
// Same goes for special triggers that we set.
subscribeToTriggers(metricSet.checker, metric.triggeredBy);
subscribeToTriggers(metricSet.checker, specialTriggers);
// :: Checker -> checkHandler
var checkId = nod.unique();
// We add the check function as one to be checked when the user
// inputs something. (There might be more than this one).
metricSet.checker.addCheck(checkFunction, checkId);
// We want the check handler to listen for results from the checker
metricSet.checkHandler.subscribeTo(checkId, metric.errorMessage, metric.defaultStatus);
if (configuration.noDom) {
eventEmitter.subscribe(metricSet.checkHandler.id);
} else {
// :: checkHandler -> domNode
// The checkHandler has its own id (and only ever needs one), so we
// just ask the domNode to listen for that.
metricSet.domNode.subscribeTo(metricSet.checkHandler.id);
}
});
// After all is done, we may have to enable/disable a submit button.
toggleSubmit();
}
/**
* If a form is added, we listen for submits, and if the has also set
* `preventSubmit` in the configuration, then we stop the commit from
* happening unless all the elements are valid.
*/
function addForm (selector) {
var form = nod.getElement(selector);
form.addEventListener('submit', possiblePreventSubmit, false);
}
// Prevent function, used above
function possiblePreventSubmit (event) {
if (configuration.preventSubmit && !areAll(nod.constants.VALID)) {
event.preventDefault();
// Show errors to the user
checkers.forEach(function (checker) {
checker.performCheck({
event: event
});
});
// Focus on the first invalid element
for (var i = 0, len = checkHandlers.length; i < len; i++) {
var checkHandler = checkHandlers[i];
if (checkHandler.getStatus().status === nod.constants.INVALID) {
checkHandler.element.focus();
break;
}
}
}
}
/**
* Removes elements completely.
*/
function removeElement (selector) {
var elements = nod.getElements(selector);
elements.forEach(function (element) {
listeners.removeItem(element);
checkers.removeItem(element);
checkHandlers.removeItem(element);
domNodes.removeItem(element);
});
}
/**
* configure
*
* Changes the configuration object used throughout the code for classes,
* delays, messages, etc.
*
* It can either be called with a key/value pair (two arguments), or with
* an object with key/value pairs.
*/
function configure (attributes, value) {
if (arguments.length > 1) {
var k = attributes;
attributes = {};
attributes[k] = value;
}
for (var key in attributes) {
configuration[key] = attributes[key];
}
if (attributes.submit || attributes.disableSubmit) {
toggleSubmit();
}
if (attributes.form) {
addForm(attributes.form);
}
}
/**
* toggleSubmit
*
* Toggles the submit button (enabled if every element is valid, otherwise
* disabled).
*/
function toggleSubmit () {
if (configuration.submit && configuration.disableSubmit) {
nod.getElement(configuration.submit).disabled = !areAll(nod.constants.VALID);
}
}
/*
* Listen to all checks, and if the user has set in the configuration to
* enable/disabled the submit button, we do that.
*/
mediator.subscribe('all', toggleSubmit);
function areAll (status) {
for (var i = 0, len = checkHandlers.length; i < len; i++) {
if (checkHandlers[i].getStatus().status !== status) {
return false;
}
}
return true;
}
function setMessageOptions (options) {
options = Array.isArray(options) ? options : [options];
options.forEach(function (option) {
var elements = nod.getElements(option.selector);
elements.forEach(function (element) {
var domNode = domNodes.findOrMake(element);
domNode.setMessageOptions(option.parent, option.errorSpan);
});
});
}
/**
* Listen to all checks and allow the user to listen in, if he set a `tap`
* function in the configuration.
*/
mediator.subscribe('all', function (options) {
if (typeof configuration.tap === 'function' && options.type === 'check') {
configuration.tap(options);
}
});
function getStatus (selector, showErrorMessage) {
var element = nod.getElement(selector),
status = checkHandlers.findOrMake(element).getStatus();
return showErrorMessage ? status : status.status;
}
function performCheck (selector) {
var cs = selector ? nod.getElements(selector).map(checkers.findOrMake) : checkers;
cs.forEach(function(checker) {
checker.performCheck();
});
}
/**
* Internal functions that are exposed to the public.
*/
var nodInstace = {
add: addMetrics,
remove: removeElement,
areAll: areAll,
getStatus: getStatus,
configure: configure,
setMessageOptions: setMessageOptions,
performCheck: performCheck
};
if (config) {
nodInstace.configure(config);
}
return nodInstace;
}
nod.constants = {
VALID: 'valid',
INVALID: 'invalid',
UNCHECKED: 'unchecked'
};
nod.classes = {
successClass: 'nod-success',
successMessageClass: 'nod-success-message',
errorClass: 'nod-error',
errorMessageClass: 'nod-error-message'
};
// Helper function to create unique id's
nod.unique = (function () {
var uniqueCounter = 0;
return function () {
return uniqueCounter++;
};
})();
/**
* makeMediator
*
* Minimal implementation of a mediator pattern, used for communication
* between checkers and checkHandlers (checkers fires events which
* handlers can subscribe to). Unique ID's are used to tell events apart.
*
* Subscribing to 'all' will give you all results from all checks.
*/
nod.makeMediator = function () {
var subscribers = [],
all = [];
return {
subscribe: function subscribe (id, fn) {
if (id === 'all') {
all.push(fn);
} else {
if (!subscribers[id]) {
subscribers[id] = [];
}
if (subscribers[id].indexOf(fn) === -1) {
subscribers[id].push(fn);
}
}
},
fire: function fire (options) {
var subscribedFunctions = subscribers[options.id].concat(all);
subscribedFunctions.forEach(function (subscribedFunction) {
subscribedFunction(options);
});
}
};
};
nod.findCollectionIndex = function (collection, element) {
for (var i in collection) {
if (collection[i].element === element) {
return i;
}
}
return -1;
};
/**
* makeCollection
*
* A minimal implementation of a "collection", inspired by collections from
* BackboneJS. Used by listeners, checkers, and checkHandlers.
*/
nod.makeCollection = function (maker) {
var collection = [];
collection.findOrMake = function (element) {
var index = nod.findCollectionIndex(collection, element);
// Found
if (index !== -1) {
return collection[index];
}
// None found, let's make one then.
var item = maker.apply(null, arguments);
collection.push(item);
return item;
};
collection.removeItem = function (element) {
var index = nod.findCollectionIndex(collection, element),
item = collection[index];
if (!item) {
return;
}
// Call .dispose() if it exists
if (typeof item.dispose === 'function') {
item.dispose();
}
// Remove item
collection.splice(index, 1);
};
return collection;
};
/**
* makeListener
*
* Takes care of listening to changes to its element and fire them off as
* events on the mediator for checkers to listen to.
*/
nod.makeListener = function (element, mediator, triggerEvents, configuration) {
var id = nod.unique(),
$element;
function changed (event) {
mediator.fire({
id: id,
event: event,
type: 'change'
});
}
element.addEventListener('input', changed, false);
element.addEventListener('change', changed, false);
element.addEventListener('blur', changed, false);
if (configuration.jQuery) {
$element = configuration.jQuery(element);
$element.on('propertychange change click keyup input paste', changed);
}
if (triggerEvents) {
triggerEvents = Array.isArray(triggerEvents) ? triggerEvents : [triggerEvents];
triggerEvents.forEach(function (eventName) {
element.addEventListener(eventName, changed, false);
});
}
function dispose () {
element.removeEventListener('input', changed, false);
element.removeEventListener('change', changed, false);
element.removeEventListener('blur', changed, false);
if ($element) {
$element.off();
}
if (triggerEvents) {
triggerEvents.forEach(function (eventName) {
element.removeEventListener(eventName, changed, false);
});
}
}
return {
element: element,
dispose: dispose,
id: id
};
};
/**
* makeChecker
*
* An "checker" communicates primarily with the mediator. It listens
* for input changes (coming from listeners), performs its checks
* and fires off results back to the mediator for checkHandlers to
* handle.
*
* The checker has a 1 to 1 relationship with an element, an
* listeners, and an checkHandler; although they may
* communicate with other "sets" of listeners, checkers and handlers.
*
* Checks are added, from the outside, and consists of a checkFunction (see
* nod.checkFunctions) and a unique id.
*/
nod.makeChecker = function (element, mediator) {
var checks = [];
function subscribeTo (id) {
mediator.subscribe(id, performCheck);
}
// Run every check function against the value of the element.
function performCheck (options) {
checks.forEach(function (check) {
check(options || {});
});
}
// Add a check function to the element. The result will be handed off
// to the mediator (for checkHandlers to evaluate).
function addCheck (checkFunction, id) {
function callback (result) {
mediator.fire({
id: id,
type: 'check',
result: result,
element: element,
validate: checkFunction.validate
});
}
checks.push(function (options) {
// If element.value is undefined, then we might be dealing with
// another type of element; like <div contenteditable='true'>
var value = element.value !== undefined ? element.value : element.innerHTML;
options.element = element;
checkFunction(callback, value, options);
});
}
return {
subscribeTo: subscribeTo,
addCheck: addCheck,
performCheck: performCheck,
element: element
};
};
/**
* makeCheckHandler
*
* Handles checks coming in from the mediator and takes care of calculating
* the state and error messages.
*
* The checkHandlers lives in one to one with the element parsed in,
* and listens for (usually) multiple error checks.
*/
nod.makeCheckHandler = function (element, mediator, configuration) {
var results = {},
id = nod.unique();
function subscribeTo (id, errorMessage, defaultStatus) {
// Create a representation of the type of error in the results
// object.
if (!results[id]) {
results[id] = {
status: defaultStatus || nod.constants.UNCHECKED,
errorMessage: errorMessage
};
}
// Subscribe to error id.
mediator.subscribe(id, checkHandler);
}
function checkHandler (result) {
results[result.id].status = result.result ? nod.constants.VALID : nod.constants.INVALID;
notifyMediator();
}
// Runs through all results to see what kind of feedback to show the
// user.
function notifyMediator () {
var status = getStatus();
// Event if might be valid we pass along an undefined errorMessage.
mediator.fire({
id: id,
type: 'result',
result: status.status,
element: element,
errorMessage: status.errorMessage
});
}
function getStatus () {
var status, errorMessage;
for (var id in results) {
status = results[id].status;
if (results[id].status === nod.constants.INVALID) {
errorMessage = results[id].errorMessage;
break;
}
}
return {
status: status,
errorMessage: errorMessage
};
}
return {
id: id,
subscribeTo: subscribeTo,
checkHandler: checkHandler,
getStatus: getStatus,
element: element
};
};
// Helper functions for `makeDomNode`.
nod.hasClass = function (className, el) {
if (el.classList) {
return el.classList.contains(className);
} else {
return !!el.className.match(new RegExp('(\\s|^)'+className+'(\\s|$)'));
}
};
nod.removeClass = function (className, el) {
if (el.classList) {
el.classList.remove(className);
} else if (nod.hasClass(className, el)) {
el.className = el.className.replace(new RegExp('(?:^|\\s)'+className+'(?!\\S)'), '');
}
};
nod.addClass = function (className, el) {
if (el.classList) {
el.classList.add(className);
} else if (!nod.hasClass(className, el)) {
el.className += ' ' + className;
}
};
nod.getParent = function (element, configuration) {
var klass = configuration.parentClass;
if (!klass) {
return element.parentNode;
} else {
klass = klass.charAt(0) === '.' ? klass.slice(1) : klass;
return nod.findParentWithClass(element.parentNode, klass);
}
};
nod.findParentWithClass = function (parent, klass) {
// Guard (only the `window` does not have a parent).
if (!parent.parentNode) {
return parent;
}
// Found it
if (nod.hasClass(klass, parent)) {
return parent;
}
// Try next parent (recursion)
return nod.findParentWithClass(parent.parentNode, klass);
};
/**
* makeDomNode
*
* This creates the error/success message behind the input element, as well
* as takes care of updating classes and taking care of its own state.
*
* The dom node is owned by checkHandler, and has a one to one
* relationship with both the checkHandler and the input element
* being checked.
*
*/
nod.makeDomNode = function (element, mediator, configuration) {
// A 'domNode' consists of two elements: a 'parent', and a 'span'. The
// parent is given as a paremeter, while the span is created and added
// as a child to the parent.
var parent = nod.getParent(element, configuration),
_status = nod.constants.UNCHECKED,
pendingUpdate = null,
span = document.createElement('span'),
customSpan = false;
span.style.display = 'none';
if (!configuration.noDom) {
parent.appendChild(span);
}
// Updates the class of the parent to match the status of the element.
function updateParent (status) {
var successClass = configuration.successClass || nod.classes.successClass,
errorClass = configuration.errorClass || nod.classes.errorClass;
switch (status) {
case nod.constants.VALID:
nod.removeClass(errorClass, parent);
nod.addClass(successClass, parent);
break;
case nod.constants.INVALID:
nod.removeClass(successClass, parent);
nod.addClass(errorClass, parent);
break;
}
}
// Updates the text and class according to the status.
function updateSpan (status, errorMessage) {
var successMessageClass = configuration.successMessageClass || nod.classes.successMessageClass,
errorMessageClass = configuration.errorMessageClass || nod.classes.errorMessageClass;
span.style.display = 'none';
switch (status) {
case nod.constants.VALID:
nod.removeClass(errorMessageClass, span);
nod.addClass(successMessageClass, span);
if (configuration.successMessage) {
span.textContent = configuration.successMessage;
span.style.display = '';
}
break;
case nod.constants.INVALID:
nod.removeClass(successMessageClass, span);
nod.addClass(errorMessageClass, span);
span.textContent = errorMessage;
span.style.display = '';
break;
}
}
function set (options) {
var status = options.result,
errorMessage = options.errorMessage;
// If the dom is showing an invalid message, we want to update the
// dom right away.
if (_status === nod.constants.INVALID || configuration.delay === 0) {
_status = status;
updateParent(status);
updateSpan(status, errorMessage);
} else {
// If the dom shows either an unchecked or a valid state
// we won't rush to tell them they are wrong. Instead
// we use a method similar to "debouncing" the update
clearTimeout(pendingUpdate);
pendingUpdate = setTimeout(function () {
_status = status;
updateParent(status);
updateSpan(status, errorMessage);
pendingUpdate = null;
}, configuration.delay || 700);
}
}
function subscribeTo (id) {
mediator.subscribe(id, set);
}
function setMessageOptions (parentContainer, message) {
if (parentContainer) {
parent = nod.getElement(parentContainer);
}
if (message) {
span.parentNode.removeChild(span); // Remove old span.
span = nod.getElement(message); // Set the new one.
customSpan = true; // So we won't delete it.
}
}
function dispose () {
// First remove any classes
nod.removeClass(configuration.errorClass || nod.classes.errorClass, parent);
nod.removeClass(configuration.successClass || nod.classes.successClass, parent);
// Then we remove the span if it wasn't one that was set by the user.
if (!customSpan) {
span.parentNode.removeChild(span);
}
}
return {
subscribeTo: subscribeTo,
element: element,
setMessageOptions: setMessageOptions,
dispose: dispose
};
};
nod.makeEventEmitter = function (mediator) {
var customEvent;
function emit (options) {
if (CustomEvent) {
customEvent = new CustomEvent('nod.validation', {detail: options});
options.element.dispatchEvent(customEvent);
} else {
throw('nod.validate tried to fire a custom event, but the browser does not support CustomEvent\'s');
}
}
function subscribe (id) {
mediator.subscribe(id, emit);
}
return {
subscribe: subscribe
};
};
/**
* getElement
*
* Returns the first element targeted by the selector. (see `getElements`)
*/
nod.getElement = function (selector) {
return nod.getElements(selector)[0];
};
/**
* getElements
*
* Takes some sort of selector, and returns an array of element(s). The applied
* selector can be one of:
*
* - Css type selector (e.g., ".foo")
* - A jQuery element (e.g., $('.foo))
* - A single raw dom element (e.g., document.getElementById('foo'))
* - A list of raw dom element (e.g., $('.foo').get())
*/
nod.getElements = function (selector) {
if (!selector) {
return [];
}
// Normal css type selector is assumed
if (typeof selector === 'string') {
// If we have jQuery, then we use that to create a dom list for us.
if (window.jQuery) {
return window.jQuery(selector).get();
}
// If not, then we do it the manual way.
var nodeList = document.querySelectorAll(selector);
return [].map.call(nodeList, function (el) { return el; });
}
// if user gave us jQuery elements
if (selector.jquery) {
return selector.get();
}
// Raw DOM element
if (selector.nodeType === 1) {
return [selector];
}
if (Array.isArray(selector)) {
var result = [];
selector.forEach(function (sel) {
var elements = nod.getElements(sel);
result = result.concat(elements);
});
return result;
}