-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathangular-m.js
More file actions
2390 lines (2277 loc) · 77.9 KB
/
angular-m.js
File metadata and controls
2390 lines (2277 loc) · 77.9 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
/**
* Angular-based model library for use in MVC framework design
* @version v2.2.1
* @link https://github.com/dlhdesign/angular-m
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
/* commonjs package manager support (eg componentjs) */
if (typeof module !== "undefined" && typeof exports !== "undefined" && module.exports === exports){
module.exports = 'angular-m';
}
(function (window, angular, undefined) {
/*jshint globalstrict:true*/
/*global angular:false*/
'use strict';
var m_isFunction = angular.isFunction,
m_isString = angular.isString,
m_isNumber = angular.isNumber,
m_isObject = angular.isObject,
m_isArray = angular.isArray,
m_isDate = function(val) { return angular.isDate(val) && !isNaN(val); },
m_isUndefined = angular.isUndefined,
m_isBoolean = function(val) { return (val === true || val === false) ? true: false; },
m_isRegEx = function(val) { return Object.prototype.toString.call(val) === '[object RegExp]' ? true : false; },
m_isNull = function(val) { return val === null; },
m_forEach = angular.forEach,
m_extend = angular.extend,
m_copy = angular.copy,
m_equals = angular.equals;
function inherit(parent, extra) {
return m_extend(new (m_extend(function () {}, { prototype: parent }))(), extra);
}
function merge(dst) {
m_forEach(arguments, function (obj) {
if (obj !== dst) {
m_forEach(obj, function (value, key) {
dst[key] = value;
});
}
});
return dst;
}
function objectKeys(object) {
var result = [];
if (m_isObject(object) === false) {
return result;
}
if (Object.keys) {
return Object.keys(object);
}
m_forEach(object, function(val, key) {
result.push(key);
});
return result;
}
function indexOf(array, value) {
var len = array.length >>> 0,
from = Number(arguments[2]) || 0;
if (Array.prototype.indexOf) {
return array.indexOf(value, Number(arguments[2]) || 0);
}
from = (from < 0) ? Math.ceil(from) : Math.floor(from);
if (from < 0) {
from += len;
}
for (; from < len; from++) {
if (from in array && array[from] === value) return from;
}
return -1;
}
function pick(obj, fields, context) {
var ret = {};
if (m_isString(fields)) {
fields = fields.split(',');
}
if (m_isFunction(fields) || (m_isArray(fields) && fields.length > 0)) {
m_forEach(obj, function (value, key) {
var include = false;
if (m_isFunction(fields)) {
include = fields.call(context || obj, key, value);
} else if (fields.indexOf(key) > -1) {
include = true;
}
if (include === true) {
ret[key] = obj[key];
} else if (include !== false) {
ret[key] = include;
}
});
}
return ret;
}
function filter(collection, callback) {
var array = m_isArray(collection),
result = array ? [] : {};
m_forEach(collection, function(val, i) {
if (callback(val, i)) {
result[array ? result.length : i] = val;
}
});
return result;
}
function map(collection, callback) {
var result = m_isArray(collection) ? [] : {};
m_forEach(collection, function(val, i) {
result[i] = callback.call(this, val, i);
});
return result;
}
/**
You'll need to include this module as a dependency within your angular app.*
<pre>
<!doctype html>
<html ng-app="myApp">
<head>
<script src="js/angular.js"></script>
<!-- Include the angular-m script -->
<script src="js/angular-m.min.js"></script>
<script>
// ...and add 'angular-m' as a dependency
var myApp = angular.module('myApp', ['angular-m']);
</script>
</head>
<body>
</body>
</html>
</pre>
*/
angular.module('angular-m', []);
function HTTPService($rootScope, $http, $q) {
var METHODS = {
read: 'GET',
update: 'PUT',
change: 'PATCH',
create: 'POST',
delete: 'DELETE'
};
var offlineError = {online: false};
function callHTTP(config, success, fail) {
var deferred = $q.defer(),
isOnline = m_isBoolean(navigator.onLine) ? navigator.onLine : true;
config = config || {};
config.method = config.method || METHODS.read;
if (isOnline === false) {
fail(offlineError);
deferred.reject(offlineError);
} else {
$http(config)
.success(function (data) {
if (m_isFunction(success)) {
success(data);
}
deferred.resolve(data);
})
.error(function (data) {
if (m_isFunction(fail)) {
fail(data);
}
deferred.reject(data);
});
}
return deferred;
}
function callRead(config, success, fail) {
config = config || {};
config.method = METHODS.read;
return this.call(config, success, fail);
}
function callUpdate(config, success, fail) {
config = config || {};
config.method = METHODS.update;
return this.call(config, success, fail);
}
function callChange(config, success, fail) {
config = config || {};
config.method = METHODS.change;
return this.call(config, success, fail);
}
function callCreate(config, success, fail) {
config = config || {};
config.method = METHODS.create;
return this.call(config, success, fail);
}
function callDelete(config, success, fail) {
config = config || {};
config.method = METHODS.delete;
return this.call(config, success, fail);
}
return {
METHODS: METHODS,
call: callHTTP,
read: callRead,
update: callUpdate,
change: callChange,
create: callCreate,
delete: callDelete,
readList: callRead,
updateList: callUpdate,
changeList: callChange,
createList: callCreate,
deleteList: callDelete
};
}
angular.module( 'angular-m.http', [] )
.service( '$mhttp', [ '$rootScope', '$http', '$q', HTTPService ] );
var RegExConstant = {
email: /^[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])+$/i,
phone: /^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/,
latLong: /^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/,
zip: /^\d{5}(?:[-\s]\d{4})?$/,
timeZone: /^GMT\s[+-]\d{2}:\d{2}$/,
timeStr: /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/
};
angular.module( 'angular-m' )
.constant( 'REGEX', RegExConstant );
function BaseFactory() {
/*jshint strict:false */
var initializing = false,
// Need to check which version of function.toString we have
superPattern = /xy/.test(function () {return 'xy';}) ? /\b_super\b/ : /.*/;
function executeQueue(idx, data) {
var self = this,
i = 0;
for(; i < self.$$cbQueue.length; i++) {
if (self.$$cbQueue[i].idx <= idx) {
if (
(self.$$cbQueue[i].type < 3 && self.$$finals[idx] && self.$$finals[idx].resolved === true) || // Success (type=1) & Always (type=2)
(self.$$cbQueue[i].type > 1 && self.$$cbQueue[i].type < 4 && self.$$finals[idx] && self.$$finals[idx].rejected === true) || // Fail (type=3) & Always (type=2)
(self.$$cbQueue[i].type === 4 && (!self.$$finals[idx] || (!self.$$finals[idx].resolved && !self.$$finals[idx].rejected))) // Progress (type=4)
) {
self.$$cbQueue[i].cb.call(self, data);
}
// If this thread is resolved or rejected, then remove the cb from the queue to keep executions faster
if (self.$$finals[idx].resolved || self.$$finals[idx].rejected) {
self.$$cbQueue.splice(i, 1);
i--;
}
}
}
}
/**
Event that triggers when the source model is cloned
@event Base#cloned
@prop {Base} clone - The new instance that was created as a result of the clone
*/
/**
Event that triggers when the model is resolved (generally when data is loaded succesfully)
@event Base#resolved
*/
/**
Event that triggers when the model is rejected (generally when a data load fails)
@event Base#rejected
*/
/**
Event that triggers when the model is notified (progress is recorded)
@event Base#notified
*/
/**
Event that triggers when the model is finalized (resolved or rejected)
@event Base#finalized
*/
/**
Event that triggers when the model is unfinalized (reset back to being neither resolved nor rejected)
@event Base#unfinalized
*/
/**
Base model that all other models will inherit from. Provides Promises/A functionality as well as publish/subscribe functionality.
@constructs Base
@prop {Object} $errors - Contains details about any error states on the instance
*/
function Base() {}
Base.prototype = {
$type: 'Base',
/**
Initialization method. Called automatically when a new instance is instantiated.
@param [data] - Initial data to populate the instance with
@param {Boolean} [forClone=false] - Whether this instance is being created as a clone or not
@return {Base} `this`
*/
init: function ( data, forClone) {
/*jshint unused:false */
var self = this;
self.$$arguments = m_copy(arguments);
self.$$cbQueue = [];
self.$$cbQueueIdx = 1;
self.$$finals = [];
self.$$listeners = {};
self.$errors = {};
return self;
},
/**
Method to clone the instance.
@return {Base} `new this.constructor(null, true)`
@fires Base#cloned
*/
clone: function () {
var self = this,
ret = new self.constructor(null, true);
ret.$$arguments = m_copy(self.$$arguments);
self.trigger('cloned', ret);
return ret;
},
/**
Indicates whether the instance has been finalized (resolved or rejected)
@arg {number} [idx=this.$$cbQueueIdx] Thread index to check
@return {Boolean}
*/
isFinal: function (idx) {
var self = this;
idx = idx || self.$$cbQueueIdx;
if (self.$$finals[idx]) {
return !!(self.$$finals[idx].resolved || self.$$finals[idx].rejected);
}
return false;
},
/**
Marks the promie thread as "resolved" (successfully complete). Sets `this.$loaded = true`, `this.$success = true`, `this.$failed = false`, and deletes `this.$busy`.
@arg [idx=this.$$cbQueueIdx] - Promise thread to resolve
@arg [data] - Data related to the resolution
@fires Base#resolved
@fires Base#finalized
@return {Base} `this`
*/
resolve: function (idx, data) {
var self = this;
idx = idx || self.$$cbQueueIdx;
self.$loaded = true;
self.$success = true;
self.$failed = false;
delete self.$busy;
if (!self.isFinal(idx)) {
self.$$finals[idx] = {
resolved: true,
data: data
};
executeQueue.call(self, idx, data);
self.trigger('resolved', data);
}
return self;
},
/**
Marks the promise thread as "rejected" (unsuccessfully complete). Sets `this.$loaded = true`, `this.$success = false`, `this.$failed = true`, and deletes `this.$busy`.
@arg [idx=this.$$cbQueueIdx] - Promise thread to reject
@arg [data] - Data related to the rejection
@fires Base#rejected
@fires Base#finalized
@returns {Base} `this`
*/
reject: function (idx, data) {
var self = this;
idx = idx || self.$$cbQueueIdx;
self.$loaded = true;
self.$success = false;
self.$failed = true;
delete self.$busy;
if (!self.isFinal(idx)) {
self.$$finals[idx] = {
rejected: true,
data: data
};
executeQueue.call(self, idx, data);
self.trigger('rejected', data);
}
return self;
},
/**
Triggers a progress step for the provided promise thread.
@arg [idx=this.$$cbQueueIdx] - Promise thread to notify of progress
@arg [data] - Data related to the progress step
@fires Base#notified
@returns {Base} `this`
*/
notify: function (idx, data) {
var self = this;
idx = idx || self.$$cbQueueIdx;
if (!self.isFinal(idx)) {
executeQueue.call(self, idx, data);
self.trigger('notified', data);
}
return self;
},
/**
"Resets" the Promise state on the instance by incrementing the current promise thread index. Sets `this.$loaded = false` and deletes `this.$success` and `this.$failed`.
@fires Base#unfinalized
@returns {number} `idx` New promise thread index
*/
unfinalize: function () {
var self = this;
self.$loaded = false;
delete self.$success;
delete self.$failed;
self.trigger('unfinalized');
return ++self.$$cbQueueIdx;
},
/**
Attaches success/fail/progress callbacks to the current promise thread, which will trigger upon the next resolve/reject call respectively or, if the current promise thread is already final, immediately.
@arg {Base~successCallback} [success]
@arg {Base~failCallback} [fail]
@arg {Base~progressCallback} [progress]
@returns {Base} `this`
*/
/**
Success callback will be triggered when/if the current promise thread is resolved.
@callback Base~successCallback
*/
/**
Fail callback will be triggered when/if the current promise thread is rejected.
@callback Base~failCallback
*/
/**
Progress callback will be triggered as the current promise thread passes through various states of progress.
@callback Base~progressCallback
*/
then: function(success, fail, progress) {
var self = this;
if (m_isFunction(success)) {
self.$$cbQueue.push({
type: 1,
cb: success,
idx: self.$$cbQueueIdx
});
}
if (m_isFunction(fail)) {
self.$$cbQueue.push({
type: 3,
cb: fail,
idx: self.$$cbQueueIdx
});
}
if (m_isFunction(progress)) {
self.$$cbQueue.push({
type: 4,
cb: progress,
idx: self.$$cbQueueIdx
});
}
if (self.$$finals[self.$$cbQueueIdx]) {
executeQueue.call(self, self.$$cbQueueIdx, self.$$finals[self.$$cbQueueIdx].data);
}
return self;
},
/**
Attaches a callback to the current promise thread which will trigger upon the next finalization or, if the current promise thread is already final, immediately.
@arg {Base~alwaysCallback} [always]
@returns {Base} `this`
*/
/**
Always callback will be triggered when/if the current promise thread is finalized (either resolved OR rejected).
@callback Base~alwaysCallback
*/
always: function (always) {
var self = this;
if (m_isFunction(always)) {
self.$$cbQueue.push({
type: 2,
cb: always,
idx: self.$$cbQueueIdx
});
}
if (self.$$finals[self.$$cbQueueIdx]) {
executeQueue.call(self, self.$$cbQueueIdx, self.$$finals[self.$$cbQueueIdx].data);
}
return self;
},
/**
Attaches success callback to the current promise thread.
@param {Base~successCallback} [success]
@return {Base} `this`
*/
success: function (cb) {
return this.then(cb);
},
/**
Attaches fail callback to the current promise thread.
@param {Base~failCallback} [fail]
@return {Base} `this`
*/
fail: function (cb) {
return this.then(null, cb);
},
/**
Attaches a progress callback to the current promise thread.
@param {Base~progressCallback} [progress]
@return {Base} `this`
*/
progress: function (cb) {
return this.then(null, null, cb);
},
/**
Attaches a listener to an event type.
@param {String} type - The type of event to listen for
@param {Function} cb - The function to trigger every time the event type occurs
@return {Base} `this`
*/
bind: function (type, cb) {
var self = this;
if (m_isString(type) && m_isFunction(cb)) {
self.$$listeners[type] = self.$$listeners[type] || [];
self.$$listeners[type].push(cb);
}
return self;
},
/**
Detaches either all listeners or just a single listener from an event type.
@param {String} type - The type of event to unbind
@param {Function} [listener] - The specific listener to unbind from the event type. If not provided, all listeners bound to the event type will be removed
@return {Base} `this`
*/
unbind: function (type, listener) {
var self = this,
idx;
if (m_isString(type) && m_isArray(self.$$listeners[type]) && self.$$listeners[type].length > 0) {
if (m_isFunction(listener)) {
self.$$listeners[type] = filter(self.$$listeners[type], function (cb) {
return cb !== listener;
});
} else {
delete self.$$listeners[type];
}
}
return self;
},
/**
Attaches a one-time listener to an event type. After triggering once, the listener will automtically be unbound.
@param {String} type - The type of event to listen for
@param {Function} cb - The function to trigger the next time the event type occurs
@return {Base} `this`
*/
one: function (type, cb) {
var self = this,
wrap;
if (m_isString(type) && m_isFunction(cb)) {
wrap = function () {
cb.call(this, arguments);
self.unbind(type, wrap);
};
self.bind(type, wrap);
}
return self;
},
/**
Triggers an event of the given type, passing any listeners the data provided.
@param {String} type - The type of event to trigger
@param [data] - Object to pass into any listeners
@return {Boolean} Returns `true` if all listeners return true, else `false`
*/
trigger: function (type, data) {
var self = this,
ret = true;
if (m_isString(type) && m_isArray(self.$$listeners[type]) && self.$$listeners[type].length > 0) {
m_forEach(self.$$listeners[type], function (cb) {
ret = cb.call(self, data, type) && ret;
});
}
return ret;
}
};
/**
Allows for model extension
@param {Object} properties - Properties to extend the new model with. Methods may call `this._super.apply(this, arguments)` to call parent model methods that are overwritten.
@extends Base
@return {Function} New constructor
*/
Base.extend = function extend(properties) {
var _super = this.prototype,
proto, key;
function construct(constructor, args) {
function Class() {
return constructor.apply(this, args);
}
Class.prototype = constructor.prototype;
return new Class();
}
function createFnProp (key, fn, super2) {
return function() {
var tmp = this._super,
ret;
this._super = super2[ key ];
ret = fn.apply(this, arguments);
if (m_isFunction(tmp)) {
this._super = tmp;
} else {
delete this._super;
}
return ret;
};
}
function Class() {
if (this.constructor !== Class) {
return construct(Class, arguments);
}
if (!initializing && m_isFunction(this.init)) {
return this.init.apply(this, arguments);
}
}
initializing = true;
proto = new this();
initializing = false;
if (!properties.$type) {
properties.$type = 'Class';
}
if (m_isFunction(proto.$preExtend)) {
properties = proto.$preExtend(properties);
}
for (key in properties) {
if (properties.hasOwnProperty(key)) {
if (m_isFunction(properties[ key ]) && m_isFunction(_super[ key ]) && superPattern.test(properties[ key ])) {
proto[ key ] = createFnProp(key, properties[ key ], _super);
} else {
proto[ key ] = properties[ key ];
}
}
}
Class.prototype = proto;
if (Object.defineProperty) {
Object.defineProperty( Class.prototype, 'constructor', {
enumerable: false,
value: Class
});
} else {
Class.prototype.constructor = Class;
}
Class.extend = extend;
return Class;
};
/**
* Return the constructor function
*/
return Base;
}
angular.module( 'angular-m' )
.factory( 'Base', BaseFactory );
function SingletonFactory(Base, REGEX) {
/**
Base model that represents a single object.
@class Singleton
@extends Base
@prop {boolean} $dirty=false - If instance has been modified since initilization or the last save, equals `true`; else `false`
@prop {boolean} $busy - If instance is currently in the middle of an API call, equals `true`; else `false`
@prop {boolean} $loaded - If instance has been loaded or instantiated with data, equals `true`; else `false`
@prop {string} $type - The type of model the instance is
*/
var Singleton = function () {},
undefinedValue = function() {};
/**
Singleton field cofiguration definition.
@typedef {FieldConfig}
@type {object}
*/
/**
* Helper functions
*/
function cap(str) {
return str.charAt(0).toLowerCase() + str.slice(1).replace(/_([a-z])/g, function ( v, l ) {
return l.toUpperCase();
});
}
function label(str) {
return str.charAt(0).toUpperCase() + str.slice(1)
.replace(/[a-z]([A-Z])/g, function (v, l, os) { // Handle "camelCase" => "Camel Case"
return str.charAt(os + 1) + ' ' + l.toUpperCase();
})
.replace(/_([a-z])/g, function (v, l) { // Handle "underscore_case" => "Underscore Case"
return ' ' + l.toUpperCase();
});
}
function setError(field, key, value) {
/*jshint validthis:true */
var self = this;
self.$errors[field] = self.$errors[field] || {};
self.$errors[field][key] = value;
self[field].$errors = self[field].$errors || {};
self[field].$errors[key] = value;
}
function validate(val, fieldConfig) {
/*jshint validthis:true */
/*jshint laxbreak:true */
var self = this,
ret = true,
mVal, matches, limit, equals;
// setError(... true) === In error state
// setError(... false) === In valid state
// ret === false if ever setError(... true)
// required
if ( fieldConfig.required === true || ( m_isFunction(fieldConfig.required) === true && fieldConfig.required.call(self, val) === true ) ) {
if ( m_isUndefined(val) || m_isNull(val) || val.length === 0 ) {
setError.call(self, fieldConfig.methodName, 'required', true );
ret = false;
} else {
setError.call(self, fieldConfig.methodName, 'required', false );
}
}
m_forEach(fieldConfig.equalsTargets, function ( target ) {
var valid;
if ( m_isFunction(self[target]) && m_equals(self[target](), val) ) {
setError.call(self, target, 'equals', false );
m_forEach(self[target].$errors, function ( value ) {
valid = value && valid;
})
self[target].$valid = !valid;
self[target].$invalid = valid;
self.trigger('validated.' + target, false);
} else {
setError.call(self, target, 'equals', true );
self[target].$valid = false;
self[target].$invalid = true;
self.trigger('validated.' + target, true);
}
});
if ( m_isUndefined(val) === false && m_isNull(val) === false ) {
// START DEFINED-ONLY CHECKS
// type
if ( indexOf(['st','nu','ob','ar','bo','dt'], fieldConfig.type ) > -1 ) {
setError.call(self, fieldConfig.methodName, 'type', false );
if ( ( fieldConfig.type === 'st' && !m_isString(val) )
|| ( fieldConfig.type === 'nu' && !m_isNumber(val) )
|| ( fieldConfig.type === 'ob' && !m_isObject(val) )
|| ( fieldConfig.type === 'ar' && !m_isArray(val) )
|| ( fieldConfig.type === 'bo' && !m_isBoolean(val) )
|| ( fieldConfig.type === 'dt' && !m_isDate(new Date(val)) )
) {
setError.call(self, fieldConfig.methodName, 'type', true );
ret = false;
}
}
// min/max
if ( m_isFunction(fieldConfig.min) === true ) {
mVal = fieldConfig.min.call(self);
} else {
mVal = fieldConfig.min;
}
if ( m_isNumber(mVal) || ( fieldConfig.type === 'dt' && m_isDate(mVal) ) ) {
if ( ( fieldConfig.type === 'st' || fieldConfig.type === 'ar' ) && val.length >= mVal ) {
setError.call(self, fieldConfig.methodName, 'min', false );
} else if ( ( !fieldConfig.type || fieldConfig.type === 'nu' ) && parseFloat( val ) >= mVal ) {
setError.call(self, fieldConfig.methodName, 'min', false );
} else if ( fieldConfig.type === 'dt' && new Date( val ) >= new Date(mVal) ) {
setError.call(self, fieldConfig.methodName, 'min', false );
} else {
setError.call(self, fieldConfig.methodName, 'min', true );
ret = false;
}
}
if ( m_isFunction(fieldConfig.max) === true ) {
mVal = fieldConfig.max.call(self);
} else {
mVal = fieldConfig.max;
}
if ( m_isNumber(mVal) || ( fieldConfig.type === 'dt' && m_isDate(mVal) ) ) {
if ( ( fieldConfig.type === 'st' || fieldConfig.type === 'ar' ) && val.length <= mVal ) {
setError.call(self, fieldConfig.methodName, 'max', false );
} else if ( ( !fieldConfig.type || fieldConfig.type === 'nu' ) && parseFloat( val ) <= mVal ) {
setError.call(self, fieldConfig.methodName, 'max', false );
} else if ( fieldConfig.type === 'dt' && new Date( val ) <= new Date(mVal) ) {
setError.call(self, fieldConfig.methodName, 'max', false );
} else {
setError.call(self, fieldConfig.methodName, 'max', true );
ret = false;
}
}
// equals
if ( m_isString(fieldConfig.equals) ) {
if ( m_isFunction(self[fieldConfig.equals]) && m_equals(self[fieldConfig.equals](), val) ) {
setError.call(self, fieldConfig.methodName, 'equals', false );
setError.call(self, fieldConfig.equals, 'equals', false );
self.trigger('validated.' + fieldConfig.equals, false);
} else {
setError.call(self, fieldConfig.methodName, 'equals', true );
setError.call(self, fieldConfig.equals, 'equals', true );
self.trigger('validated.' + fieldConfig.equals, true);
ret = false;
}
} else if ( m_isArray(fieldConfig.equals) ) {
equals = false;
m_forEach(fieldConfig.equals, function (target) {
if ( m_isFunction(self[target]) ) {
if ( m_equals(self[target](), val) ) {
equals = true;
setError.call(self, target, 'equals', false );
self.trigger('validated.' + target, false);
} else {
setError.call(self, target, 'equals', true );
self.trigger('validated.' + target, true);
}
}
});
setError.call(self, fieldConfig.methodName, 'equals', !equals );
ret = ret && equals;
}
// not-equals
if ( m_isString(fieldConfig.notEquals) ) {
if ( m_isFunction(self[fieldConfig.notEquals]) && !m_equals(self[fieldConfig.notEquals](), val) ) {
setError.call(self, fieldConfig.methodName, 'notEquals', false );
setError.call(self, fieldConfig.notEquals, 'notEquals', false );
self.trigger('validated.' + fieldConfig.notEquals, false);
} else {
setError.call(self, fieldConfig.methodName, 'notEquals', true );
setError.call(self, fieldConfig.notEquals, 'notEquals', true );
self.trigger('validated.' + fieldConfig.notEquals, true);
ret = false;
}
} else if ( m_isArray(fieldConfig.notEquals) ) {
notEquals = false;
m_forEach(fieldConfig.notEquals, function (target) {
if ( m_isFunction(self[target]) ) {
if ( !m_equals(self[target](), val) ) {
setError.call(self, target, 'notEquals', false );
self.trigger('validated.' + target, false);
} else {
notEquals = true;
setError.call(self, target, 'notEquals', true );
self.trigger('validated.' + target, true);
}
}
});
setError.call(self, fieldConfig.methodName, 'notEquals', !notEquals );
ret = ret && notEquals;
}
// END DEFINED-ONLY CHECKS
}
// matches
if ( m_isRegEx(fieldConfig.matches) ) {
matches = fieldConfig.matches.test(val) || ( m_isUndefined(val) || m_isNull(val) || val.length === 0 );
setError.call(self, fieldConfig.methodName, 'matches', !matches );
ret = matches && ret;
}
// limit
if ( m_isUndefined(fieldConfig.limit) === false && m_isNull(fieldConfig.limit) === false ) {
if ( m_isUndefined(val) || m_isNull(val) || val.length === 0 ) {
setError.call(self, fieldConfig.methodName, 'limit', false );
} else if ( m_isArray(fieldConfig.limit) || m_isObject(fieldConfig.limit) ) {
limit = false;
m_forEach(fieldConfig.limit, function (lim) {
if ( m_isObject( lim ) === true && !m_isNull(lim.value) && !m_isUndefined(lim.value) ) {
limit = limit || m_equals(lim.value, val);
} else {
limit = limit || m_equals(lim, val);
}
});
// limit === true when a match was found, so invert for setError
setError.call(self, fieldConfig.methodName, 'limit', !limit );
ret = limit && ret;
} else if ( m_isString(fieldConfig.limit) || m_isNumber(fieldConfig.limit) || m_isBoolean(fieldConfig.limit) ) {
limit = m_equals(fieldConfig.limit, val);
setError.call(self, fieldConfig.methodName, 'limit', !limit );
ret = limit && ret;
}
}
return ret;
}
Singleton = Base.extend(
/** @lends Singleton.prototype */
{
$type: 'Singleton',
$preExtend: function (properties) {
if ( m_isObject(this.fields) ) {
properties.fields = merge( {}, this.fields, properties.fields );
m_forEach(properties.fields, function (value, key) {
if ( value === false ) {
delete properties.fields[key];
}
});
}
return properties;
},
/**
Instantiates the Singleton by setting up all the field getter/setters.
@override
*/
init: function (data, forClone) {
/*jshint unused:false */
var self = this._super.apply(this, arguments),
equalsTargets = {},
defaultFields = [];
self.$$merged = self.$$data = data || false;
self.$$setData = {};
self.$$defaults = {};
self.$loaded = data ? true : false;
self.$dirty = false;
self.$pristine = true;
self.$busy = false;
self.$valid = true;
self.$invalid = false;
self.$$fieldConfig = false;
self.each(function (fieldConfig) {
var field, f, target;
if ( fieldConfig.getter !== undefined && !m_isFunction(fieldConfig.getter) ) {
throw new Error('Singleton Init Error: "getter" must be undefined/null or a function');
}
if ( fieldConfig.setter !== undefined && !m_isFunction(fieldConfig.setter) ) {
throw new Error('Singleton Init Error: "setter" must be undefined/null or a function');
}
function getter() {
var ret,
field = fieldConfig.key;
//console.log('getter: ' + (fieldConfig.key ? fieldConfig.key : key) + ' = ' + self.get()[ fieldConfig.key ? fieldConfig.key : key ] );
if ( fieldConfig.$$getterCacheSet === true ) {
return fieldConfig.$$getterCache;
}
if ( fieldConfig.getter ) {
ret = fieldConfig.getter.call(self, fieldConfig);
if ( ret === undefined ) {
return ret;
}
} else {
field = field.split( '.' );
ret = self.get()[ field.shift() ];
while ( field.length > 0 ) {
if ( m_isObject( ret ) === false ) {
return null;
}
ret = ret[ field.shift() ];
}
if ( ( ret === null || ret === undefined ) && fieldConfig.default !== undefined ) {
if ( m_isFunction(fieldConfig.default) === true ) {
ret = fieldConfig.default.call(self, fieldConfig);
} else {
ret = fieldConfig.default;
}
}
if ( m_isFunction(fieldConfig.mutateGet) === true ) {
ret = fieldConfig.mutateGet.call(self, ret, fieldConfig);
}
}
if ( fieldConfig.cache !== false ) {
fieldConfig.$$getterCacheSet = true;
fieldConfig.$$getterCache = ret;
}
return ret;
}
function setter(val) {
var field = fieldConfig.key,
f, target;