/
jermaine.js
1339 lines (1132 loc) · 48.6 KB
/
jermaine.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
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
"use strict";
if (this == null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 0) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
}
}
/*global describe, it, beforeEach, expect, xit, jasmine */
(function (ns) {
"use strict";
var namespace = function (ns, aliases, func) {
var nsRegExp = /^([a-zA-Z]+)(\.[a-zA-Z]*)*$/,
nsArray,
currentNS,
i;
//check to assure ns is a properly formatted namespace string
if (ns.match(nsRegExp) === null || ns === "window") {
throw new Error("namespace: " + ns + " is a malformed namespace string");
}
//check to assure that if alias is defined that func is defined
if (aliases !== undefined && func === undefined) {
if (typeof (aliases) === "function") {
func = aliases;
aliases = undefined;
} else if (typeof (aliases) === "object") {
throw new Error("namespace: if second argument exists, final function argument must exist");
} else if (typeof (aliases) !== "object") {
throw new Error("namespace: second argument must be an object of aliased local namespaces");
}
} else if (typeof (aliases) !== "object" && typeof (func) === "function") {
throw new Error("namespace: second argument must be an object of aliased local namespaces");
}
//parse namespace string
nsArray = ns.split(".");
//set the root namespace to window (if it's not explictly stated)
if (nsArray[0] === "window") {
currentNS = window;
} else {
currentNS = (window[nsArray[0]] === undefined) ? window[nsArray[0]] = {} : window[nsArray[0]];
}
//confirm func is actually a function
if (func !== undefined && typeof (func) !== "function") {
throw new Error("namespace: last parameter must be a function that accepts a namespace parameter");
}
//build namespace
for (i = 1; i < nsArray.length; i = i + 1) {
if (currentNS[nsArray[i]] === undefined) {
currentNS[nsArray[i]] = {};
}
currentNS = currentNS[nsArray[i]];
}
//namespaces.push(currentNS);
//namespace = currentNS;
//if the function was defined, but no aliases run it on the current namespace
if (aliases === undefined && func) {
func(currentNS);
} else if (func) {
for (i in aliases) {
if (aliases.hasOwnProperty(i)) {
aliases[i] = namespace(aliases[i]);
}
}
func.call(aliases, currentNS);
}
//return namespace
return currentNS;
};
return namespace(ns, function (exports) {
exports.namespace = namespace;
});
}("window.jermaine.util"));
window.jermaine.util.namespace("window.jermaine.util", function (ns) {
"use strict";
var EventEmitter = function () {
var that = this,
listeners = {};
//an registers event and a listener
this.on = function (event, listener) {
if (typeof(event) !== "string") {
throw new Error("EventEmitter: first argument to 'on' should be a string");
}
if (typeof(listener) !== "function") {
throw new Error("EventEmitter: second argument to 'on' should be a function");
}
if (!listeners[event]) {
listeners[event] = [];
}
listeners[event].push(listener);
return that;
};
//alias addListener
this.addListener = this.on;
this.once = function (event, listener) {
var f = function () {
listener(arguments);
that.removeListener(event, f);
};
that.on(event, f);
return that;
};
this.removeListener = function (event, listener) {
var index;
if (typeof(event) !== "string") {
throw new Error("EventEmitter: first parameter to removeListener method must be a string representing an event");
}
if (typeof(listener) !== "function") {
throw new Error("EventEmitter: second parameter must be a function to remove as an event listener");
}
if (listeners[event] === undefined || listeners[event].length === 0) {
throw new Error("EventEmitter: there are no listeners registered for the '" + event + "' event");
}
index = listeners[event].indexOf(listener);
if (index !== -1) {
//remove it from the list
listeners[event].splice(index,1);
}
return that;
};
this.removeAllListeners = function (event) {
if (typeof(event) !== "string") {
throw new Error("EventEmitter: parameter to removeAllListeners should be a string representing an event");
}
if (listeners[event] !== undefined) {
listeners[event] = [];
}
return that;
};
this.setMaxListeners = function (number) {
return that;
};
//get the listeners for an event
this.listeners = function (event) {
if (typeof(event) !== 'string') {
throw new Error("EventEmitter: listeners method must be called with the name of an event");
} else if (listeners[event] === undefined) {
return [];
}
return listeners[event];
};
//execute each of the listeners in order with the specified arguments
this.emit = function (event, data) {
var i,
params;
if (arguments.length > 1) {
params = [];
}
for (i = 1; i < arguments.length; ++i) {
params.push(arguments[i]);
}
if (listeners[event] !== undefined) {
for (i = 0; i < listeners[event].length; i=i+1) {
listeners[event][i].apply(this, params);
}
}
};
return that;
}; //end EventEmitter
ns.EventEmitter = EventEmitter;
});
window.jermaine.util.namespace("window.jermaine", function (ns) {
"use strict";
var that = this,
Validator,
validators = {};
Validator = function (spec) {
var validatorFunction = function (arg) {
var result,
resultObject = {},
errorMessage;
result = spec.call(resultObject, arg);
if (!result) {
errorMessage = resultObject.message || "validator failed with parameter " + arg;
throw new Error(errorMessage);
}
return result;
};
return validatorFunction;
};
Validator.addValidator = function (name, v) {
if (name === undefined || typeof(name) !== "string") {
throw new Error("addValidator requires a name to be specified as the first parameter");
}
if (v === undefined || typeof(v) !== "function") {
throw new Error("addValidator requires a function as the second parameter");
}
if (validators[name] === undefined) {
validators[name] = function (expected) {
return new Validator(function (val) {
var resultObject = {"actual":val, "param":val},
result = v.call(resultObject, expected);
this.message = resultObject.message;
return result;
});
};
} else {
throw new Error("Validator '" + name +"' already defined");
}
};
Validator.getValidator = function (name) {
var result;
if (name === undefined) {
throw new Error("Validator: getValidator method requires a string parameter");
} else if (typeof (name) !== "string") {
throw new Error("Validator: parameter to getValidator method must be a string");
}
result = validators[name];
if (result === undefined) {
throw new Error("Validator: '" + name + "' does not exist");
}
return result;
};
Validator.validators = function () {
var prop,
result = [];
for (prop in validators) {
if (validators.hasOwnProperty(prop)) {
result.push(prop);
}
}
return result;
};
Validator.addValidator("isGreaterThan", function (val) {
this.message = this.param + " should be greater than " + val;
return this.param > val;
});
Validator.addValidator("isLessThan", function (val) {
this.message = this.param + " should be less than " + val;
return this.param < val;
});
Validator.addValidator("isA", function (val) {
var types = ["string", "number", "boolean", "function", "object"];
if (typeof(val) === "string" && types.indexOf(val) > -1) {
this.message = this.param + " should be a " + val;
return typeof(this.param) === val;
} else if (val === 'integer') {
// special case for 'integer'; since javascript has no integer type,
// just check for number type and check that it's numerically an int
if (this.param.toString !== undefined) {
this.message = this.param.toString() + " should be an integer";
} else {
this.message = "parameter should be an integer";
}
return (typeof(this.param) === 'number') && (parseInt(this.param,10) === this.param);
} else if (typeof(val) === "string") {
throw new Error("Validator: isA accepts a string which is one of " + types);
} else {
throw new Error("Validator: isA only accepts a string for a primitive types for the time being");
}
});
validators.isAn = validators.isA;
Validator.addValidator("isOneOf", function (val) {
this.message = this.param + " should be one of the set: " + val;
return val.indexOf(this.param) > -1;
});
ns.Validator = Validator;
});
/**
* Attr
*
* Creates an encapsulated, chainable attribute that are validated by
* user-specified validation functions and can be attached to an arbitrary
* JavaScript object. They can also call user-specified listeners upon being
* accessed or changed.
*
* Jermaine models hold and manipulate Attr (and AttrList) objects until they
* are attached to an object.
*/
/*!
*
* Notes and ToDos:
* + what about isNotGreaterThan()?, isNotLessThan()? Or, better still: a
* general 'not' operator, as in jasmine?
*
* + Attr should be decoupled from AttrList, see the clone() method
*
* + See issue 24 on github
*/
window.jermaine.util.namespace("window.jermaine", function (ns) {
"use strict";
var Attr = function (name) {
var validators = [],
that = this,
errorMessage = "invalid setter call for " + name,
defaultValueOrFunction,
i,
prop,
addValidator,
immutable = false,
validator,
listeners = {},
AttrList = window.jermaine.AttrList,
Validator = window.jermaine.Validator;
// check for errors with constructor parameters
if (name === undefined || typeof(name) !== 'string') {
throw new Error("Attr: constructor requires a name parameter " +
"which must be a string");
}
// set up the validator that combines all validators
validator = function (thingBeingValidated) {
for (i = 0; i < validators.length; ++i) {
validators[i](thingBeingValidated);
}
return true;
};
////////////////////////////////////////////////////////////////////////
/////////////////////////// MODIFIERS //////////////////////////////////
////////////////////////////////////////////////////////////////////////
/**
* Validate this attribute with the given validator. This also allows
* this.message to be overridden to specify the error message on
* validation failure.
*
* Examples:
*
* age.validatesWith(function (age) {
* this.message = "age must be between 18 and 99, " + age +
* " fails.";
* return age >= 18 && age <= 99;
* });
*
* name.validatesWith(function (name) {
* this.message = "name must be a string and contain at least" +
* " 3 letters, " + name + " fails.";
* return typeof(name) === "string && name.length >= 3;
* });
*
*
* @param {Function} returns true if the argument passes validation
*/
this.validatesWith = function (v) {
if (typeof(v) === 'function') {
validators.push(new Validator(v));
return this;
} else {
throw new Error("Attr: validator must be a function");
}
};
/**
* Assign a default value to all attributes of this type. The default
* value may be an explicit value or object, or it may be a function
* that returns a default value.
*
* Examples:
*
* @param {value} the explicit default value, or a function that
* returns the default value
*/
this.defaultsTo = function (value) {
defaultValueOrFunction = value;
return this;
};
/**
* Make this attribute read-only. If a setter is called on this
* attribute, it will throw an error
*
* Examples:
*/
this.isReadOnly = function () {
immutable = true;
return this;
};
/**
* Make this attribute writable. Note that this is the default for all
* attributes, but this may be called if an attribute has been set to
* read only and then needs to be changed back
*
* Examples:
*/
this.isWritable = function () {
immutable = false;
return this;
};
/**
* Sets up a listener for 'sets' or 'gets' to this attribute. It throws
* an error if the event is not "set" or "get", and if a setter is
* already set up for the event, it overrides it.
*
* Examples:
*
* @param {event} String that can only be "set" or "get"
* @param {listener} Function that is called when the event occurs
*/
this.on = function (event, listener) {
if (event !== "set" && event !== "get") {
throw new Error("Attr: first argument to the 'on' method " +
"should be 'set' or 'get'");
} else if (typeof(listener) !== "function") {
throw new Error("Attr: second argument to the 'on' method " +
"should be a function");
} else {
listeners[event] = listener;
}
};
////////////////////////////////////////////////////////////////////////
/////////////////////////// END MODIFIERS //////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
/////////////////////// GETTERS ////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
/**
* Returns the name of this attribute
*/
this.name = function () {
return name;
};
/**
* Returns a function that combines all of the validators into
* a single function that returns true or false.
*/
this.validator = function () {
return validator;
};
////////////////////////////////////////////////////////////////////////
/////////////////////// END GETTERS ////////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
/////////////////////// SYNTACTIC SUGAR ////////////////////////////////
////////////////////////////////////////////////////////////////////////
/**
* An alias for this object, for readability when calling multiple
* modifiers
*
* Examples:
*/
this.and = this;
/**
* An alias for this object, for readability.
*
* Examples:
*/
this.which = this;
/**
* An alias for isReadOnly
*/
this.isImmutable = this.isReadOnly;
/**
* An alias for isWritable
*/
this.isMutable = this.isWritable;
////////////////////////////////////////////////////////////////////////
/////////////////////// END SYNTACTIC SUGAR ////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
/////////////////////// UTILITIES //////////////////////////////////////
////////////////////////////////////////////////////////////////////////
/**
* Returns an attribute with the same modifiers, defaultValue, and
* validators. This is used in Jermaine's approach to inheritance.
*
* Examples:
*/
this.clone = function () {
var result,
i;
// set the result to the default attribute or attribute list
// TODO: figure out how to make this work without explicitly
// knowing about AttrList so it can be decoupled from this
// code
result = this instanceof AttrList?new AttrList(name):new Attr(name);
// add this attributes validators to the new attribute
for (i = 0; i < validators.length; ++i) {
result.validatesWith(validators[i]);
}
// set up the same default for the new attribute
result.defaultsTo(defaultValueOrFunction);
// if the this attr is immutable, the cloned attr should also be
// immutable
if (immutable) {
result.isImmutable();
}
return result;
};
/**
* This attaches the attribute to a concrete object. It adds the
* getter/setter function to the object, and captures the actual
* value of the attribute in a closure.
*
* The resulting getter/setter calls all validators on the parameter
* and calls the appropriate listener on this attribute. It also
* returns the object itself so that attribute setters can be chained.
*
* Examples:
*
* @param {obj} the object to which this attribute will be attached
*/
this.addTo = function (obj) {
var attribute,
listener,
defaultValue;
if (!obj || typeof(obj) !== 'object') {
throw new Error("Attr: addAttr method requires an object " +
"parameter");
}
// This is the attribute getter/setter method that gets addded to
// the object
obj[name] = function (newValue) {
var preValue;
if (newValue !== undefined) {
// setter
if (immutable && attribute !== undefined) {
throw new Error("cannot set the immutable property " +
name + " after it has been set");
} else if (!validator(newValue)) {
throw new Error(errorMessage);
} else {
// get the oldValue
preValue = attribute;
// first set the value
attribute = newValue;
// call the set listener
if (listeners.set !== undefined) {
listeners.set.call(obj, newValue, preValue);
}
}
return obj;
} else {
// call the get listener
if (listeners.get !== undefined) {
listeners.get.call(obj, attribute);
}
return attribute;
}
};
// assign the default value, depends on whether it is a function
// or an explicit value
defaultValue = typeof(defaultValueOrFunction) === 'function'?
defaultValueOrFunction():
defaultValueOrFunction;
// call the setter with the defaultValue upon attaching it to the
// object
if (defaultValue !== undefined && validator(defaultValue)) {
obj[name](defaultValue);
} else if (defaultValue !== undefined && !validator(defaultValue)) {
throw new Error("Attr: Default value of " + defaultValue +
" does not pass validation for " + name);
}
};
////////////////////////////////////////////////////////////////////////
/////////////////////// END UTILITIES //////////////////////////////////
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
/////////////////////// VALIDATOR RELATED //////////////////////////////
////////////////////////////////////////////////////////////////////////
// add a single validator object to the attribute
addValidator = function (name) {
that[name] = function (param) {
validators.push(Validator.getValidator(name)(param));
return that;
};
};
// the Validator object contains several default validators
// that need to be attached to all Attrs
for (i = 0; i < Validator.validators().length; ++i) {
addValidator(Validator.validators()[i]);
}
////////////////////////////////////////////////////////////////////////
/////////////////////// END VALIDATOR RELATED //////////////////////////
////////////////////////////////////////////////////////////////////////
};
// export Attr to the specified namespace
ns.Attr = Attr;
});
window.jermaine.util.namespace("window.jermaine", function (ns) {
"use strict";
function AttrList(name) {
var that = this;
//this is where the inheritance happens now
ns.Attr.call(this, name);
var delegate = function (obj, func) {
return function () { return obj[func].apply(obj, arguments); };
};
//syntactic sugar to keep things grammatically correct
this.validateWith = this.validatesWith;
//disable defaultsTo and isImmutable until we figure out how to make it make sense
this.defaultsTo = function () {
//no op
};
this.isImmutable = function () {
//no op
};
this.isMutable = function () {
//no op
};
this.eachOfWhich = this;
this.addTo = function (obj) {
var prop,
arr = [],
actualList = {};
if(!obj || typeof(obj) !== 'object') {
throw new Error("AttrList: addTo method requires an object parameter");
} else {
actualList.pop = delegate(arr, "pop");
actualList.add = function (obj) {
if ((that.validator())(obj)) {
arr.push(obj);
return this;
} else {
throw new Error(that.errorMessage());
}
};
actualList.replace = function (index, obj) {
if ((typeof(index) !== 'number') || (parseInt(index, 10) !== index)) {
throw new Error("AttrList: replace method requires index parameter to be an integer");
}
if (index < 0 || index >= this.size()) {
throw new Error("AttrList: replace method index parameter out of bounds");
}
if (!(that.validator())(obj)) {
throw new Error(that.errorMessage());
}
arr[index] = obj;
return this;
};
actualList.at = function (index) {
if (index < 0 || index >= this.size()) {
throw new Error("AttrList: Index out of bounds");
}
return arr[index];
};
//to keep things more java-y
actualList.get = actualList.at;
actualList.size = function () {
return arr.length;
};
actualList.toJSON = function (JSONreps) {
var result = [],
i, j;
//check to make sure the current list is not in JSONreps
if (JSONreps !== undefined) {
for (i = 0;i < JSONreps.length; ++i) {
if (JSONreps[i].object === this) {
result = JSONreps[i].JSONrep;
}
}
}
for (i = 0; i < arr.length; ++i) {
if (arr[i].toJSON) {
result.push(arr[i].toJSON(JSONreps));
} else {
result.push(arr[i]);
}
}
return result;
};
obj[name] = function () {
return actualList;
};
}
};
}
//this needs to stay if we're going to use instanceof
//but note we override all of the methods via delegation
//so it's not doing anything except for making an AttrList
//an instance of Attr
AttrList.prototype = new window.jermaine.Attr(name);
ns.AttrList = AttrList;
});
window.jermaine.util.namespace("window.jermaine", function (ns) {
"use strict";
var Method = function (name, method) {
if (!name || typeof(name) !== "string") {
throw new Error("Method: constructor requires a name parameter which must be a string");
} else if (!method || typeof(method) !== "function") {
throw new Error("Method: second parameter must be a function");
}
this.addTo = function (obj) {
if (!obj || typeof(obj) !== 'object') {
throw new Error("Method: addTo method requires an object parameter");
}
obj[name] = method;
};
};
ns.Method = Method;
});
window.jermaine.util.namespace("window.jermaine", function (ns) {
"use strict";
var Model = function (specification) {
var methods = {},
attributes = {},
pattern,
modified = true,
requiredConstructorArgs = [],
optionalConstructorArgs = [],
parents = [],
Method = ns.Method,
Attr = ns.Attr,
AttrList = ns.AttrList,
EventEmitter = ns.util.EventEmitter,
property,
listProperties,
updateConstructor,
isImmutable,
initializer = function () {},
constructor = function () {},
model = function () {
if (modified) {
//validate the model if it has been modified
model.validate();
updateConstructor();
}
return constructor.apply(this, arguments);
};
//temporary fix so API stays the same
if (arguments.length > 1) {
specification = arguments[arguments.length-1];
}
//handle specification function
if (specification && typeof(specification) === "function") {
model = new Model();
specification.call(model);
return model;
} else if (specification) {
throw new Error("Model: specification parameter must be a function");
}
/********** BEGIN PRIVATE METHODS ****************/
/* private method that abstracts hasA/hasMany */
var hasAProperty = function (type, name) {
var Property,
methodName,
attribute;
//Property is one of Attr or AttrList
Property = type==="Attr"?Attr:AttrList;
//methodName is either hasA or hasMany
methodName = type==="Attr"?"hasA":"hasMany";
modified = true;
if (typeof(name) === 'string') {
attribute = new Property(name);
attributes[name] = attribute;
return attribute;
} else {
throw new Error("Model: " + methodName + " parameter must be a string");
}
};
/* private method that abstracts attribute/method */
property = function (type, name) {
var result;
if (typeof(name) !== "string") {
throw new Error("Model: expected string argument to " + type + " method, but recieved " + name);
}
result = type==="attribute" ? attributes[name] : methods[name];
if (result === undefined) {
throw new Error("Model: " + type + " " + name + " does not exist!");
}
return result;
};
/* private method that abstracts attributes/methods */
listProperties = function (type) {
var i,
list = [],
properties = type==="attributes"?attributes:methods;
for (i in properties) {
if (properties.hasOwnProperty(i)) {
list.push(i);
}
}
return list;
};
/* private function that updates the constructor */
updateConstructor = function () {
constructor = function () {
var i, j,
err,
attribute,
attributeList = model.attributes(),
methodList = model.methods(),
emitter = new EventEmitter(),
attr,
attrChangeListeners = {},
setHandler,
lastListener,
addProperties;
if (!(this instanceof model)) {
throw new Error("Model: instances must be created using the new operator");
}
////////////////////////////////////////////////////////////////
////////////// PUBLIC API FOR ALL INSTANCES ////////////////////
////////////////////////////////////////////////////////////////
/**
* Returns the EventEmitter associated with this instance.
*
*/
this.emitter = function () {
return emitter;
};
/**
* Registers a listener for this instance's changes.
*
*/
this.on = this.emitter().on;
/**
* Emits an event
*/
this.emit = this.emitter().emit;
/**
* Returns a JSON representation of this instance.
*
*/
this.toJSON = function (JSONreps) {
var attributeValue,
i, j,
thisJSONrep = {},
attributeJSONrep;
if (JSONreps === undefined) {
// first call
JSONreps = [];
JSONreps.push({object:this, JSONrep:thisJSONrep});
} else if (typeof(JSONreps) !== "object") {
// error condition
throw new Error("Instance: toJSON should not take a parameter (unless called recursively)");
} else {
// find the current JSON representation of this object, if it exists
for (i = 0; i < JSONreps.length; ++i) {
if (JSONreps[i].object === this) {
thisJSONrep = JSONreps[i].JSONrep;
}
}
}
for (i = 0; i < attributeList.length; ++i) {
attributeJSONrep = null;