forked from VoliJS/NestedTypes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnestedtypes.js
More file actions
1791 lines (1439 loc) · 56.9 KB
/
Copy pathnestedtypes.js
File metadata and controls
1791 lines (1439 loc) · 56.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
/**
* Backbone.NestedTypes 1.0.0 <https://github.com/Volicon/backbone.nestedTypes>
* (c) 2015 Vlad Balin & Volicon
* Released under MIT @license
*/
/**
* Date.parse with progressive enhancement for ISO 8601 <https://github.com/csnover/js-iso8601>
* © 2011 Colin Snover <http://zetafleet.com>
* Released under MIT @license
*/
(function(root, factory) {
if(typeof exports === 'object') {
module.exports = factory(require('underscore'), require('backbone'));
}
else if(typeof define === 'function' && define.amd) {
define(['underscore', 'backbone'], factory);
}
else {
root.Nested = factory(root._, root.Backbone);
}
}(this, function( _, Backbone ) {
var require = function(name) {
return { underscore: _, backbone : Backbone }[name];
};
require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
// Options wrapper for chained and safe type specs...
// --------------------------------------------------
require( './object+' );
var trigger3 = require( './backbone+' ).Events.trigger3,
modelSet = require( './modelset' ),
genericIsChanged = modelSet.isChanged,
setSingleAttr = modelSet.setSingleAttr;
var primitiveTypes = {
string : String,
number : Number,
boolean : Boolean
};
// list of simple accessor methods available in options
var availableOptions = [ 'triggerWhenChanged', 'changeEvents', 'parse', 'clone', 'toJSON', 'value', 'cast', 'create', 'name', 'value',
'type' ];
var Options = Object.extend( {
_options : {}, // attribute options
Attribute : null, // default attribute spec when no type is given, is set to Attribute below
properties : {
has : function(){ return this; }
},
constructor : function( spec ){
// special option used to guess types of primitive values and to distinguish value from type
if( 'typeOrValue' in spec ){
var typeOrValue = spec.typeOrValue,
primitiveType = primitiveTypes[ typeof typeOrValue ];
if( primitiveType ){
spec = { type : primitiveType, value : typeOrValue };
}
else{
spec = typeof typeOrValue == 'function' ? { type : typeOrValue } : { value : typeOrValue };
}
}
this._options = {};
this.options( spec );
},
// get hooks stored as an array
get : function( getter ){
var options = this._options;
options.get = options.get ? options.get.unshift( getter ) : [ getter ];
return this;
},
// set hooks stored as an array
set : function( setter ){
var options = this._options;
options.set = options.set ? options.set.push( setter ) : [ setter ];
return this;
},
// events must be merged
events : function( events ){
this._options.events = Object.assign( this._options.events || {}, events );
return this;
},
// options must be merged using rules for individual accessors
options : function( options ){
for( var i in options ){
this[ i ]( options[ i ] );
}
return this;
},
// construct attribute with a given name and proper type.
createAttribute : function( name ){
var options = this._options,
Type = options.type ? options.type.Attribute : this.Attribute;
if( options.changeEvents ) options.triggerWhenChanged = options.changeEvents;
return new Type( name, options );
}
} );
availableOptions.forEach( function( name ){
Options.prototype[ name ] = function( value ){
this._options[ name ] = value;
return this;
};
} );
function chainHooks( array ){
var l = array.length;
return l === 1 ? array[ 0 ] : function( value, name ){
var res = value;
for( var i = 0; i < l; i++ ){
res = array[ i ].call( this, res, name );
}
return res;
};
}
var transform = {
hookAndCast : function( val, options, model, name ){
var value = this.cast( val, options, model, name ),
prev = model.attributes[ name ];
if( this.isChanged( value, prev ) ){
value = this.set.call( model, value, name );
return value === undefined ? prev : this.cast( value, options, model );
}
return value;
},
hook : function( value, options, model, name ){
var prev = model.attributes[ name ];
if( this.isChanged( value, prev ) ){
var changed = this.set.call( model, value, name );
return changed === undefined ? prev : changed;
}
return value;
},
delegateAndMore : function( val, options, model, attr ){
return this.delegateEvents( this._transform( val, options, model, attr ), options, model, attr );
}
};
// Base class for Attribute metatype
// ---------------------------------
var Attribute = Object.extend( {
name : null,
type : null,
value : undefined,
// cast function
// may be overriden in subclass
cast : null, // function( value, options, model ),
// get and set hooks...
get : null,
set : null,
// user events
events : null, // { event : handler, ... }
// system events
__events : null, // { event : handler, ... }
// create empty object passing backbone options to constructor...
// must be overriden for backbone types only
create : function( options ){ return new this.type(); },
// optimized general purpose isEqual function for typeless attributes
// must be overriden in subclass
isChanged : genericIsChanged,
// generic clone function for typeless attributes
// Must be overriden in sublass
clone : function( value, options ){
if( value && typeof value === 'object' ){
var proto = Object.getPrototypeOf( value );
if( proto.clone ){
// delegate to object's clone if it exist
return value.clone( options );
}
if( options && options.deep && proto === Object.prototype || proto === Array.prototype ){
// attempt to deep copy raw objects, assuming they are JSON
return JSON.parse( JSON.stringify( value ) );
}
}
return value;
},
toJSON : function( value, key ){
return value && value.toJSON ? value.toJSON() : value;
},
// must be overriden for backbone types...
createPropertySpec : function(){
return (function( self, name, get ){
return {
// call to optimized set function for single argument. Doesn't work for backbone types.
set : function( value ){ setSingleAttr( this, name, value, self ); },
// attach get hook to the getter function, if present
get : get ? function(){ return get.call( this, this.attributes[ name ], name ); } :
function(){ return this.attributes[ name ]; }
}
})( this, this.name, this.get );
},
// automatically generated optimized transform function
// do not touch.
_transform : null,
transform : function( value ){ return value; },
// delegate user and system events on attribute transform
delegateEvents : function( value, options, model, name ){
var prev = model.attributes[ name ];
if( this.isChanged( prev, value ) ){ //should be changed only when attr is really replaced.
prev && prev.trigger && model.stopListening( prev );
if( value && value.trigger ){
if( this.events ){
model.listenTo( value, this.events );
}
if( this.__events ){
model.listenTo( value, this.__events );
}
}
trigger3( model, 'replace:' + name, model, value, prev );
}
return value;
},
constructor : function( name, spec ){
this.name = name;
Object.transform( this, spec, function( value, name ){
if( name === 'events' && this.events ){
return Object.assign( this.events, value );
}
if( name === 'get' ){
if( this.get ){
value.unshift( this.get );
}
return chainHooks( value );
}
if( name === 'set' ){
if( this.set ){
value.push( this.set );
}
return chainHooks( value );
}
return value;
}, this );
this.initialize( spec );
// assemble optimized transform function...
if( this.cast ){
this.transform = this._transform = this.cast;
}
if( this.set ){
this.transform = this._transform = this.cast ? transform.hookAndCast : transform.hook;
}
if( this.events || this.__events ){
this.transform =
this._transform ? transform.delegateAndMore : this.delegateEvents;
}
}
}, {
attach : (function(){
function options( spec ){
spec || ( spec = {} );
spec.type || ( spec.type = this );
return new Options( spec );
}
function value( value ){
return new Options( { type : this, value : value } );
}
return function(){
for( var i = 0; i < arguments.length; i++ ){
var Type = arguments[ i ];
Type.attribute = Type.options = options;
Type.value = value;
Type.Attribute = this;
Object.defineProperty( Type, 'has', {
get : function(){
// workaround for sinon.js and other libraries overriding 'has'
return this._has || this.options();
},
set : function( value ){ this._has = value; }
} );
}
};
})()
} );
Options.prototype.Attribute = Attribute;
Options.prototype.attribute = Options.prototype.options;
function createOptions( spec ){
return new Options( spec );
}
createOptions.Type = Attribute;
createOptions.create = function( options, name ){
if( !( options && options instanceof Options ) ){
options = new Options( { typeOrValue : options } );
}
return options.createAttribute( name );
};
module.exports = createOptions;
},{"./backbone+":2,"./modelset":7,"./object+":8}],2:[function(require,module,exports){
/* Backbone core extensions: bug fixes and optimizations
- Use Object+ for all backbone objects
- Fix for Events.listenTo to support message maps
- optimized trigger functions
* (c) Vlad Balin & Volicon, 2015
* ------------------------------------------------------------- */
var Class = require( './object+' ),
Backbone = require( 'backbone' );
module.exports = Backbone;
// Workaround for backbone 1.2.0 listenTo event maps bug
var Events = Backbone.Events,
bbListenTo = Events.listenTo;
Events.listenTo = function( obj, events ){
if( typeof events === 'object' ){
for( var event in events ) bbListenTo.call( this, obj, event, events[ event ] );
return this;
}
return bbListenTo.apply( this, arguments );
};
// Update Backbone objects to use event patches and Object+
[ 'Model', 'Collection', 'View', 'Router', 'History' ].forEach( function( name ){
var Type = Backbone[ name ];
Type.prototype.listenTo = Events.listenTo;
Object.extend.attach( Type );
});
// Make Object.extend classes capable of sending and receiving Backbone Events...
Object.assign( Class.prototype, Events );
// So hard to believe :) You won't. Optimized JIT-friendly event trigger functions to be used from model.set
// Two specialized functions for event triggering...
Events.trigger2 = function( self, name, a, b ){
var _events = self._events;
if( _events ){
_fireEvent2( _events[ name ], a, b );
_fireEvent3( _events.all, name, a, b );
}
};
Events.trigger3 = function( self, name, a, b, c ){
var _events = self._events;
if( _events ){
_fireEvent3( _events[ name ], a, b, c );
_fireEvent4( _events.all, name, a, b, c );
}
};
// ...and specialized functions with triggering loops. Crappy JS JIT loves these small functions and code duplication.
function _fireEvent2( events, a, b ){
if( events )
for( var i = 0, l = events.length, ev; i < l; i ++ )
(ev = events[i]).callback.call(ev.ctx, a, b);
}
function _fireEvent3( events, a, b, c ){
if( events )
for( var i = 0, l = events.length, ev; i < l; i ++ )
(ev = events[i]).callback.call(ev.ctx, a, b, c);
}
function _fireEvent4( events, a, b, c, d ){
if( events )
for( var i = 0, l = events.length, ev; i < l; i ++ )
(ev = events[i]).callback.call(ev.ctx, a, b, c, d);
}
},{"./object+":8,"backbone":"backbone"}],3:[function(require,module,exports){
var Backbone = require( './backbone+' ),
Model = require( './model' ),
error = require( './errors' ),
_ = require( 'underscore' );
var CollectionProto = Backbone.Collection.prototype;
function wrapCall( func ){
return function(){
if( !this.__changing++ ){
this.trigger( 'before:change' );
}
var res = func.apply( this, arguments );
if( !--this.__changing ){
this.trigger( 'after:change' );
}
return res;
};
}
module.exports = Backbone.Collection.extend( {
triggerWhenChanged : Backbone.VERSION >= '1.2.0' ? 'update change reset' : 'add remove change reset',
__class : 'Collection',
model : Model,
isValid : function( options ){
return this.every( function( model ){
return model.isValid( options );
} );
},
get : function( obj ){
if( obj == null ){
return void 0;
}
return typeof obj === 'object' ? this._byId[ obj.id ] || this._byId[ obj.cid ] : this._byId[ obj ];
},
deepClone : function(){ return this.clone( { deep : true } ); },
clone : function( options ){
var models = options && options.deep ?
this.map( function( model ){
return model.clone( options );
} ) : this.models;
return new this.constructor( models );
},
__changing : 0,
set : wrapCall( function( models, options ){
if( models ){
if( typeof models !== 'object' || !( models instanceof Array || models instanceof Model ||
Object.getPrototypeOf( models ) === Object.prototype ) ){
error.wrongCollectionSetArg( this, models );
}
}
return CollectionProto.set.call( this, models, options );
} ),
remove : wrapCall( CollectionProto.remove ),
add : wrapCall( CollectionProto.add ),
reset : wrapCall( CollectionProto.reset ),
sort : wrapCall( CollectionProto.sort ),
getModelIds : function(){ return _.pluck( this.models, 'id' ); }
}, {
// Cache for subsetOf collection subclass.
__subsetOf : null,
defaults : function( attrs ){
return this.prototype.model.extend( { defaults : attrs } ).Collection;
},
extend : function(){
// Need to subsetOf cache when extending the collection
var This = Backbone.Collection.extend.apply( this, arguments );
This.__subsetOf = null;
return This;
}
} );
},{"./backbone+":2,"./errors":4,"./model":6,"underscore":"underscore"}],4:[function(require,module,exports){
require( './object+' );
function format( value ){
return typeof value === 'string' ? '"' + value + '"' : value;
}
Object.assign( Object.extend.error, {
argumentIsNotAnObject : function( context, value ){
//throw new TypeError( 'Attribute hash is not an object in ' + context.__class + '.set(', value, ')' );
console.error( '[Type Error] Attribute hash is not an object in ' +
context.__class + '.set(', format( value ), '); this =', context );
},
unknownAttribute : function( context, name, value ){
if( context.suppressTypeErrors ) return;
console.warn( '[Type Error] Attribute has no default value in ' +
context.__class + '.set( "' + name + '",', format( value ), '); this =', context );
},
wrongCollectionSetArg : function( context, value ){
//throw new TypeError( 'Wrong argument type in ' + context.__class + '.set(' + value + ')' );
console.error( '[Type Error] Wrong argument type in ' +
context.__class + '.set(', format( value ), '); this =', context );
}
});
module.exports = Object.extend.error;
},{"./object+":8}],5:[function(require,module,exports){
// Date.parse with progressive enhancement for ISO 8601 <https://github.com/csnover/js-iso8601>
// © 2011 Colin Snover <http://zetafleet.com>
// Released under MIT license.
// Attribute Type definitions for core JS types
// ============================================
var attribute = require( './attribute' ),
modelSet = require( './modelset' ),
Model = require( './model' ),
Collection = require( './collection' );
// Constructors Attribute
// ----------------
attribute.Type.extend( {
cast : function( value ){
return value == null || value instanceof this.type ? value : new this.type( value );
},
clone : function( value, options ){
// delegate to clone function or deep clone through serialization
return value.clone ? value.clone( value, options ) : this.cast( JSON.parse( JSON.stringify( value ) ) );
}
} ).attach( Function.prototype );
// Date Attribute
// ----------------------
var numericKeys = [ 1, 4, 5, 6, 7, 10, 11 ],
msDatePattern = /\/Date\(([0-9]+)\)\//,
isoDatePattern = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/;
function parseDate( date ){
var msDate, timestamp, struct, minutesOffset = 0;
if( msDate = msDatePattern.exec( date ) ){
timestamp = Number( msDate[ 1 ] );
}
else if( ( struct = isoDatePattern.exec( date )) ){
// avoid NaN timestamps caused by �undefined� values being passed to Date.UTC
for( var i = 0, k; ( k = numericKeys[ i ] ); ++i ){
struct[ k ] = +struct[ k ] || 0;
}
// allow undefined days and months
struct[ 2 ] = (+struct[ 2 ] || 1) - 1;
struct[ 3 ] = +struct[ 3 ] || 1;
if( struct[ 8 ] !== 'Z' && struct[ 9 ] !== undefined ){
minutesOffset = struct[ 10 ] * 60 + struct[ 11 ];
if( struct[ 9 ] === '+' ){
minutesOffset = 0 - minutesOffset;
}
}
timestamp =
Date.UTC( struct[ 1 ], struct[ 2 ], struct[ 3 ], struct[ 4 ], struct[ 5 ] + minutesOffset, struct[ 6 ],
struct[ 7 ] );
}
else{
timestamp = Date.parse( date );
}
return timestamp;
}
attribute.Type.extend( {
cast : function( value ){
return value == null || value instanceof Date ? value :
new Date( typeof value === 'string' ? parseDate( value ) : value )
},
toJSON : function( value ){ return value && value.toJSON(); },
isChanged : function( a, b ){ return ( a && +a ) !== ( b && +b ); },
clone : function( value ){ return new Date( +value ); }
} ).attach( Date );
// Primitive Types
// ----------------
// Global Mock for missing Integer data type...
// -------------------------------------
Integer = function( x ){ return x ? Math.round( x ) : 0; };
attribute.Type.extend( {
create : function(){ return this.type(); },
toJSON : function( value ){ return value; },
cast : function( value ){ return value == null ? null : this.type( value ); },
isChanged : function( a, b ){ return a !== b; },
clone : function( value ){ return value; }
} ).attach( Number, Boolean, String, Integer );
// Array Type
// ---------------
attribute.Type.extend( {
toJSON : function( value ){ return value; },
cast : function( value ){
// Fix incompatible constructor behaviour of Array...
return value == null || value instanceof Array ? value : [ value ];
}
} ).attach( Array );
// Backbone Attribute
// ----------------
// helper attrSpec mock to force attribute update
var bbForceUpdateAttr = new ( attribute.Type.extend( {
isChanged : function(){ return true; }
} ) );
var setAttrs = modelSet.setAttrs,
setSingleAttr = modelSet.setSingleAttr;
attribute.Type.extend( {
create : function( options ){ return new this.type( null, options ); },
clone : function( value, options ){ return value && value.clone( options ); },
toJSON : function( value ){ return value && value.toJSON(); },
isChanged : function( a, b ){ return a !== b; },
isBackboneType : true,
isModel : true,
createPropertySpec : function(){
// if there are nested changes detection enabled, disable optimized setter
if( this.__events ){
return (function( self, name, get ){
return {
set : function( value ){
var attrs = {};
attrs[ name ] = value;
setAttrs( this, attrs );
},
get : get ? function(){ return get.call( this, this.attributes[ name ], name ); } :
function(){ return this.attributes[ name ]; }
}
})( this, this.name, this.get );
}
else{
return attribute.Type.prototype.createPropertySpec.call( this );
}
},
cast : function( value, options, model, name ){
var incompatibleType = value != null && !( value instanceof this.type ),
existingModelOrCollection = model.attributes[ name ];
if( incompatibleType ){
if( existingModelOrCollection ){ // ...delegate update for existing object 'set' method
if( options && options.parse && this.isModel ){ // handle inconsistent backbone's parse implementation
value = existingModelOrCollection.parse( value );
}
existingModelOrCollection.set( value, options );
value = existingModelOrCollection;
}
else{ // ...or create a new object, if it's not exist
value = new this.type( value, options );
}
}
return value;
},
initialize : function( spec ){
var name = this.name,
triggerWhenChanged = this.triggerWhenChanged || spec.type.prototype.triggerWhenChanged;
this.isModel = this.type.prototype instanceof Model;
if( triggerWhenChanged ){
// for collection, add transactional methods to join change events on bubbling
this.__events = this.isModel ? {} : {
'before:change' : modelSet.__begin,
'after:change' : modelSet.__commit
};
this.__events[ triggerWhenChanged ] = function handleNestedChange(){
var attr = this.attributes[ name ];
if( this.__duringSet ){
this.__nestedChanges[ name ] = attr;
}
else{
setSingleAttr( this, name, attr, bbForceUpdateAttr );
}
};
}
}
} ).attach( Model, Collection );
},{"./attribute":1,"./collection":3,"./model":6,"./modelset":7}],6:[function(require,module,exports){
var BaseModel = require( './backbone+' ).Model,
modelSet = require( './modelset' ),
attrOptions = require( './attribute' ),
error = require( './errors' ),
_ = require( 'underscore' ),
ModelProto = BaseModel.prototype;
var setSingleAttr = modelSet.setSingleAttr,
setAttrs = modelSet.setAttrs,
applyTransform = modelSet.transform;
function cloneAttrs( attrSpecs, attrs, options ){
for( var name in attrs ){
attrs[ name ] = attrSpecs[ name ].clone( attrs[ name ], options );
}
return attrs;
}
var Model = BaseModel.extend( {
triggerWhenChanged : 'change',
properties : {
id : {
get : function(){
var name = this.idAttribute;
// TODO: get hook doesn't work for idAttribute === 'id'
return name === 'id' ? this.attributes.id : this[ name ];
},
set : function( value ){
var name = this.idAttribute;
setSingleAttr( this, name, value, this.__attributes[ name ] );
}
}
},
__attributes : { id : attrOptions( { value : undefined } ).createAttribute( 'id' ) },
__class : 'Model',
__duringSet : 0,
defaults : function(){ return {}; },
__begin : modelSet.__begin,
__commit : modelSet.__commit,
set : function( a, b, c ){
switch( typeof a ){
case 'string' :
var attrSpec = this.__attributes[ a ];
if( attrSpec && !attrSpec.isBackboneType && !c ){
return setSingleAttr( this, a, b, attrSpec );
}
var attrs = {};
attrs[ a ] = b;
return setAttrs( this, attrs, c );
case 'object' :
if( a && Object.getPrototypeOf( a ) === Object.prototype ){
return setAttrs( this, a, b );
}
default :
error.argumentIsNotAnObject( this, a );
}
},
// Return model's value for dot-separated 'deep reference'.
// Model id and cid are allowed for collection elements.
// If path is not exist, 'undefined' is returned.
// model.deepGet( 'a.b.c123.x' )
deepGet : function( name ){
var path = name.split( '.' ), value = this;
for( var i = 0, l = path.length; value && i < l; i++ ){
value = value.get ? value.get( path[ i ] ) : value[ path[ i ] ];
}
return value;
},
// Set model's value for dot separated 'deep reference'.
// If model doesn't exist at some path, create default models
// if options.nullify is given, assign attributes with nulls
deepSet : function( name, value, options ){
var path = name.split( '.' ),
l = path.length - 1,
model = this,
attr = path[ l ];
for( var i = 0; i < l; i++ ){
var current = path[ i ],
next = model.get ? model.get( current ) : model[ current ];
// Create models in path, if they are not exist.
if( !next ){
var attrSpecs = model.__attributes;
if( attrSpecs ){
// If current object is model, create default attribute
var newModel = attrSpecs[ current ].create( options );
// If created object is model, nullify attributes when requested
if( options && options.nullify && newModel.__attributes ){
var nulls = new newModel.Attributes( {} );
for( var key in nulls ){
nulls[ key ] = null;
}
newModel.set( nulls );
}
model[ current ] = next = newModel;
}
else{
return;
} // silently fail in other case
}
model = next;
}
return model.set ? model.set( attr, value, options ) : model[ attr ] = value;
},
constructor : function( attributes, opts ){
var attrSpecs = this.__attributes,
attrs = attributes || {},
options = opts || {};
this.cid = _.uniqueId( 'c' );
this.attributes = {};
if( options.collection ){
this.collection = options.collection;
}
if( options.parse ){
attrs = this.parse( attrs, options ) || {};
}
if( typeof attrs !== 'object' || Object.getPrototypeOf( attrs ) !== Object.prototype ){
error.argumentIsNotAnObject( this, attrs );
attrs = {};
}
attrs = options.deep ?
cloneAttrs( attrSpecs, new this.Attributes( attrs ), options ) :
this.defaults( attrs, options );
// Execute attributes transform function instead of this.set
applyTransform( this, attrs, attrSpecs, options );
this.attributes = attrs;
this.changed = {};
this.initialize.apply( this, arguments );
},
// override get to invoke native getter...
get : function( name ){ return this[ name ]; },
// override clone to pass options to constructor
clone : function( options ){
return new this.constructor( this.attributes, options );
},
// Create deep copy for all nested objects...
deepClone : function(){ return this.clone( { deep : true } ); },
// Support for nested models and objects.
// Apply toJSON recursively to produce correct JSON.
toJSON : function(){
var res = {},
attrs = this.attributes, attrSpecs = this.__attributes;
for( var key in attrs ){
var value = attrs[ key ], attrSpec = attrSpecs[ key ],
toJSON = attrSpec && attrSpec.toJSON;
if( toJSON ){
res[ key ] = toJSON.call( this, value, key );
}
}
return res;
},
parse : function( resp ){ return this._parse( resp ); },
_parse : _.identity,
isValid : function( options ){
// todo: need to do something smart with validation logic
// something declarative on attributes level, may be
return ModelProto.isValid.call( this, options ) && _.every( this.attributes, function( attr ){
if( attr && attr.isValid ){
return attr.isValid( options );
}
return attr instanceof Date ? !_.isNaN( attr.getTime() ) : !_.isNaN( attr );
} );
},
_ : _ // add underscore to be accessible in templates
}, {
// shorthand for inline nested model definitions
defaults : function( attrs ){ return this.extend( { defaults : attrs } ); },
// extend Model and its Collection
extend : function( protoProps, staticProps ){
var This = Object.extend.call( this );
This.Collection = this.Collection.extend();
return protoProps ? This.define( protoProps, staticProps ) : This;
},
// define Model and its Collection. All the magic starts here.
define : function( protoProps, staticProps ){
var Base = Object.getPrototypeOf( this.prototype ).constructor,
spec = createDefinition( protoProps, Base ),
This = this;
Object.extend.Class.define.call( This, spec, staticProps );
// define Collection
var collectionSpec = { model : This };
spec.urlRoot && ( collectionSpec.url = spec.urlRoot );
This.Collection.define( _.defaults( protoProps.collection || {}, collectionSpec ) );
return This;
}
} );
// Create model definition from protoProps spec.
function createDefinition( protoProps, Base ){
var defaults = protoProps.defaults || protoProps.attributes || {},
defaultsAsFunction = typeof defaults == 'function' && defaults,
baseAttrSpecs = Base.prototype.__attributes;
// Support for legacy backbone defaults as functions.
if( defaultsAsFunction ){
defaults = defaults();
}
var attrSpecs = Object.transform( {}, defaults, attrOptions.create );
// Create attribute for idAttribute, if it's not declared explicitly
var idAttribute = protoProps.idAttribute;
if( idAttribute && !attrSpecs[ idAttribute ] ){
attrSpecs[ idAttribute ] = attrOptions( { value : undefined } ).createAttribute( idAttribute );
}
// Prevent conflict with backbone model's 'id' property
if( attrSpecs[ 'id' ] ){
attrSpecs[ 'id' ].createPropertySpec = false;
}
var allAttrSpecs = _.defaults( {}, attrSpecs, baseAttrSpecs ),
Attributes = createCloneCtor( allAttrSpecs );
return _.extend( _.omit( protoProps, 'collection', 'attributes' ), {
__attributes : new Attributes( allAttrSpecs ),
_parse : create_parse( allAttrSpecs, attrSpecs ) || Base.prototype._parse,
defaults : defaultsAsFunction || createDefaults( allAttrSpecs ),
properties : createAttrsNativeProps( protoProps.properties, attrSpecs ),
Attributes : Attributes
} );
}
// Create attributes 'parse' option function only if local 'parse' options present.
// Otherwise return null.
function create_parse( allAttrSpecs, attrSpecs ){
var statements = [ 'var a = this.__attributes;' ],
create = false;
for( var name in allAttrSpecs ){
// Is there any 'parse' option in local model definition?