This repository has been archived by the owner on Mar 31, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
loader.js
3702 lines (3247 loc) · 108 KB
/
loader.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
/**
* util.js
*
* This sets up our util object, which defines a way to export Composer
* components and also defines a number of helper functions the rest of the
* system will use.
* -----------------------------------------------------------------------------
*
* Composer.js is an MVC framework for creating and organizing javascript
* applications. For documentation, please visit:
*
* http://lyonbros.github.com/composer.js/
*
* -----------------------------------------------------------------------------
*
* Copyright (c) 2011, Lyon Bros LLC. (http://www.lyonbros.com)
*
* Licensed under The MIT License.
* Redistributions of files must retain the above copyright notice.
*/
(function() {
"use strict";
if(!this.Composer) {
var Composer = {
version: '1.3.6',
// note: this used to be "export" but IE is a whiny little bitch, so now
// we're sup3r 1337 h4x0r5
exp0rt: function(obj) {
Object.keys(obj).forEach(function(key) {
Composer[key] = obj[key];
});
}
};
this.Composer = Composer;
}
var Composer = this.Composer;
/**
* You must override this function in your app.
*/
var sync = function(method, model, options) { return options.success(); };
// Used to override the default sync function.
var set_sync = function(syncfn) { this.Composer.sync = syncfn; }.bind(this);
// a closure that returns incrementing integers. these will be unique across
// the entire app since only one counter is instantiated
var cid = (function() {
var counter = 1;
return function(inc) { return 'c'+counter++; };
})();
// wraps error callbacks for syncing functions
var wrap_error = function(callback, model, options) {
return function(resp) {
if(callback) {
callback(model, resp, options);
} else {
this.fire_event('error', options, model, resp, options);
}
};
};
// Composer equality function. Does deep-inpection and is able to tell the
// difference between {key: 3} and {key: 3, key2: 4} (_.eq had problems with
// this back in the day).
var eq = function(a, b) {
if ( a === b ) return true;
if(a instanceof Function) return false;
if(typeof(a) != typeof(b)) return false;
if((a && a.constructor) && !b || !b.constructor) return false;
if((b && b.constructor) && !a || !a.constructor) return false;
if(a && b && a.constructor != b.constructor) return false;
if(a instanceof Array || Object.prototype.toString.call(a) === '[object Array]') {
if(a.length != b.length) return false;
// TODO: check if array indexes are always sequential
for(var i = 0, n = a.length; i < n; i++) {
if(!b.hasOwnProperty(i)) return false;
if(!eq(a[i], b[i])) return false;
}
} else if(a instanceof Date && b instanceof Date) {
return a.getTime() == b.getTime();
} else if(a instanceof Object) {
for( var p in b ) {
if( b.hasOwnProperty(p) && ! a.hasOwnProperty(p) ) return false;
}
for( var p in a ) {
if ( ! a.hasOwnProperty( p ) ) continue;
if ( ! b.hasOwnProperty( p ) ) return false;
if ( a[ p ] === b[ p ] ) continue;
if ( typeof( a[ p ] ) !== "object" ) return false;
if ( ! eq( a[ p ], b[ p ] ) ) return false;
}
} else if(a != b) {
return false;
}
return true;
};
// create an extension function that merges specific properties from
// inherited objects
var merge_extend = function(cls, properties) {
var _extend = cls.extend;
cls.extend = function(def, base) {
base || (base = this);
var attr = base.prototype;
properties.forEach(function(prop) {
def[prop] = Composer.object.merge({}, attr[prop], def[prop]);
});
var cls = _extend.call(base, def);
Composer.merge_extend(cls, properties);
return cls;
}
};
// some Mootools-reminiscent object utilities Composer uses
var array = {
erase: function(arr, item) {
for(var i = arr.length - 1; i >= 0; i--) {
if(arr[i] === item) arr.splice(i, 1);
}
},
is: (function() {
return ('isArray' in Array) ?
Array.isArray :
function(obj) {
return obj instanceof Array || Object.prototype.toString.call(obj) === '[object Array]'
}
})()
};
var object = {
each: function(obj, fn, bind) {
if(!obj) return;
bind || (bind = this);
Object.keys(obj).forEach(function(key) {
(fn.bind(bind))(obj[key], key)
});
},
clone: function(obj, options) {
options || (options = {});
if(options.deep) return JSON.parse(JSON.stringify(obj));
var clone = {};
Object.keys(obj).forEach(function(key) {
clone[key] = obj[key];
});
return clone;
},
merge: function(to, _) {
var args = Array.prototype.slice.call(arguments, 1);
args.forEach(function(obj) {
if(!obj) return;
Object.keys(obj).forEach(function(key) {
to[key] = obj[key];
});
});
return to;
},
set: function(object, key, value) {
object || (object = {});
var paths = key.split('.');
var obj = object;
for(var i = 0, n = paths.length; i < n; i++) {
var path = paths[i];
if(i == n - 1) {
obj[path] = value;
break;
}
if(!obj[path]) {
obj[path] = {};
} else if(typeof(obj) != 'object' || Composer.array.is(obj)) {
obj[path] = {};
}
obj = obj[path];
}
return object;
},
get: function(object, key) {
object || (object = {});
var paths = key.split('.');
var obj = object;
for(var i = 0, n = paths.length; i < n; i++) {
var path = paths[i];
var type = typeof(obj[path]);
if(type == 'undefined') {
return obj[path];
}
obj = obj[path];
}
return obj;
}
};
var promisify = function(poptions) {
poptions || (poptions = {});
var convert = function(type, asyncs) {
if(!Composer[type]) return;
Object.keys(asyncs).forEach(function(key) {
var spec = asyncs[key];
var options_idx = spec.options_idx || 0;
var names = spec.names || ['success', 'error'];
var _old = Composer[type].prototype[key];
Composer[type].prototype[key] = function() {
var args = Array.prototype.slice.call(arguments, 0);
if(args.length < options_idx) {
var _tmp = new Array(options_idx);
args.forEach(function(item, i) { _tmp[i] = item; });
args = _tmp;
}
if(!args[options_idx]) args[options_idx] = {};
var _self = this;
var options = args[options_idx];
if(options.promisified) return _old.apply(_self, args);
if(poptions.warn && (options[names[0]] || options[names[1]])) {
console.warn('Composer: promisify: attempting to pass callbacks to promisified function: ', type, key);
}
return new Promise(function(resolve, reject) {
if(names[0]) options[names[0]] = resolve;
if(names[1]) options[names[1]] = function(_, err) { reject(err); };
options.promisified = true;
_old.apply(_self, args);
});
};
});
};
convert('Model', {
fetch: {},
save: {},
destroy: {}
});
convert('Collection', {
fetch: {},
reset_async: {options_idx: 1, names: ['complete']}
});
convert('Controller', {
html: {options_idx: 1, names: ['complete']}
});
// NOTE: you'd think that because ListController.html() calls the parent
// Controller.html() (which is promisified) but because the
// ListController is defined *before* we call promisify, it's html()
// parent function is the un-promisified Controller.html(). we don't
// have a way to "reach into" the parent chain and replace it, so we
// hack it by promisifying ListController.html()
convert('ListController', {
html: {options_idx: 1, names: ['complete']}
});
};
this.Composer.exp0rt({
sync: sync,
set_sync: set_sync,
cid: cid,
wrap_error: wrap_error,
eq: eq,
merge_extend: merge_extend,
array: array,
object: object,
promisify: promisify
});
}).apply((typeof exports != 'undefined') ? exports : this);
/**
* class.js
*
* Defines the base class system used by Composer (can be standlone as well)
* -----------------------------------------------------------------------------
*
* Composer.js is an MVC framework for creating and organizing javascript
* applications. For documentation, please visit:
*
* http://lyonbros.github.com/composer.js/
*
* -----------------------------------------------------------------------------
*
* Copyright (c) 2011, Lyon Bros LLC. (http://www.lyonbros.com)
*
* Licensed under The MIT License.
* Redistributions of files must retain the above copyright notice.
*/
(function() {
"use strict";
var Composer = this.Composer;
/**
* like typeof, but returns if it's an array or null
*/
var typeOf = function(obj) {
if(obj == null) return 'null';
var type = typeof(obj);
if(type != 'object') return type;
if(obj instanceof Array) return 'array';
return type;
};
/**
* Merge object `from` into `into`
*/
var merge = function(into, from, options) {
options || (options = {});
var keys = Object.keys(from);
var transform = options.transform;
for(var i = 0, n = keys.length; i < n; i++) {
var k = keys[i];
if(transform) transform(into, from, k);
into[k] = from[k];
}
return into;
};
/**
* Given an object, copy the subobjects/subarrays recursively
*/
var copy = function(obj) {
// we can't do Object.keys or hasOwnProperty here because we actually
// want to look at all inherited objects as well as owned objects.
for(var k in obj) {
var val = obj[k];
var type = typeOf(val);
if(type == 'object') {
obj[k] = copy(merge({}, val));
} else if(type == 'array') {
obj[k] = val.map(copy);
}
}
return obj;
};
/**
* Create a new class prototype from the given base class.
*/
var create = function(base) {
if('create' in Object) {
// create the new object from the prototype
var prototype = Object.create(base.prototype);
} else {
// of we won't have Object.create, then we need to let the object
// know we want a bare instance (without initializing it)
base.$initializing = true;
var prototype = new base();
delete base.$initializing;
}
var cls = function Omni() {
// don't run the ctor if we're just trying to get a prototype
if(cls.$initializing) return this;
// if we don't copy the objects in the prototype, then if we have an
// object in the prototype like so:
// {
// count: {x: 0},
// ...
// }
//
// Then by doing `new Counter().count.x = 5`, we set x=5 for the
// entire prototype, and hence all the subsequent instantiations of
// the class.
copy(this);
this.$state = {parents: {}, fn: []};
return this.initialize ? this.initialize.apply(this, arguments) : this;
};
cls.$constructor = prototype.$constructor = cls;
cls.prototype = prototype;
cls.prototype.$parent = base;
return cls;
};
/**
* Wraps an overriding method to track its state so get_parent() can pull
* out the right function.
*/
var extend_parent = function(to, from, k) {
return function() {
if(!this.$state.parents[k]) this.$state.parents[k] = [];
this.$state.parents[k].push(from);
this.$state.fn.push(k);
var val = to.apply(this, arguments);
this.$state.fn.pop();
this.$state.parents[k].pop();
return val;
};
};
/**
* Takes care of "parentizing" overridden methods when merging prototypes
*/
var do_extend = function(to_prototype, from_prototype) {
return merge(to_prototype, from_prototype, {
transform: function(into, from, k) {
if(typeof into[k] != 'function' || into[k].prototype.$parent || typeof from[k] != 'function' || from[k].prototype.$parent) return false;
from[k] = extend_parent(from[k], into[k], k);
from[k].$parent = into[k];
}
});
};
/**
* Once base to rule them all (and in the darkness bind them)
*/
var Base = function() {};
/**
* Main extension method, creates a new class from the given object
*/
Base.extend = function(obj) {
var base = this;
var cls = create(base);
do_extend(cls.prototype, obj);
cls.extend = Base.extend;
cls.prototype.$get_parent = function() {
var k = this.$state.fn[this.$state.fn.length - 1];
if(!k) return false;
var parents = this.$state.parents[k];
var parent = parents[parents.length - 1];
return parent || false;
};
cls.prototype.parent = function() {
var fn = this.$get_parent();
if(fn) return fn.apply(this, arguments);
throw 'Class.js: Bad parent method: '+ this.$state.fn[this.$state.fn.length - 1];
};
return cls;
};
// wrap base class so we can call it directly or as .extend()
function Class(obj) { return Base.extend(obj); };
Class.extend = Class;
Composer.exp0rt({ Class: Class });
}).apply((typeof exports != 'undefined') ? exports : this);
/**
* event.js
*
* Defines the eventing fabric used throughout Composer
* -----------------------------------------------------------------------------
*
* Composer.js is an MVC framework for creating and organizing javascript
* applications. For documentation, please visit:
*
* http://lyonbros.github.com/composer.js/
*
* -----------------------------------------------------------------------------
*
* Copyright (c) 2011, Lyon Bros LLC. (http://www.lyonbros.com)
*
* Licensed under The MIT License.
* Redistributions of files must retain the above copyright notice.
*/
(function() {
"use strict";
var Composer = this.Composer;
var make_lookup_name = function(event_name, bind_name) {
return event_name + '@' + bind_name;
};
var Event = Composer.Class({
_handlers: {},
_handler_names: {},
/**
* Bind a function to an event. Optionally allows naming the binding so
* it can be removed later on without the reference to the bound
* function.
*/
bind: function(event_name, fn, bind_name) {
if(Composer.array.is(event_name)) {
event_name.forEach(function(ev) {
this.bind(ev, fn, bind_name);
}.bind(this));
return this;
}
if(bind_name) this.unbind(event_name, bind_name);
if(!this._handlers[event_name]) this._handlers[event_name] = [];
var eventhandlers = this._handlers[event_name];
eventhandlers.push(fn);
if(bind_name) {
this._handler_names[make_lookup_name(event_name, bind_name)] = fn;
}
return this;
},
/**
* Bind a function to an event, but clear the binding out once the event
* has been triggered once.
*/
bind_once: function(event_name, fn, bind_name) {
bind_name || (bind_name = null);
var wrapped_function = function() {
this.unbind(event_name, wrapped_function)
fn.apply(this, arguments);
}.bind(this);
return this.bind(event_name, wrapped_function, bind_name);
},
/**
* Unbind an event/function pair. If function_or_name contains a
* non-function value, the value is used in a name lookup instead. This
* allows removing an event/function binding by its name (as specified
* by `bind_name` in the bind function) which can be nice when the
* original function is no longer in scope.
*/
unbind: function(event_name, function_or_name) {
if(!event_name) return this.wipe();
if(Composer.array.is(event_name)) {
event_name.forEach(function(ev) {
this.unbind(ev, function_or_name);
}.bind(this));
return this;
}
if(!function_or_name) return this.unbind_all(event_name);
var is_fn = function_or_name instanceof Function;
var lookup_name = is_fn ? null : make_lookup_name(event_name, function_or_name);
var fn = is_fn ? function_or_name : this._handler_names[lookup_name];
if(!fn) return this;
if(!is_fn) delete this._handler_names[lookup_name];
if(!this._handlers[event_name]) return this;
var idx = this._handlers[event_name].indexOf(fn);
if(idx < 0) return this;
this._handlers[event_name].splice(idx, 1);
return this;
},
/**
* Unbind all handlers for the given event name.
*/
unbind_all: function(event_name) {
delete this._handlers[event_name];
return this;
},
/**
* Wipe out all handlers for a dispatch object.
*/
wipe: function(options) {
options || (options = {});
this._handlers = {};
this._handler_names = {};
return this;
},
/**
* Trigger an event.
*/
trigger: function(event_name, _) {
var args = Array.prototype.slice.call(arguments, 0);
var handlers = this._handlers[event_name] || [];
var catch_all = this._handlers['all'] || [];
// we do a copy so unbinds during a trigger don't corrupt the
// handler array
var handlers_copy = handlers.slice(0);
var handlers_args = args.slice(1);
for(var i = 0, n = handlers_copy.length; i < n; i++) {
handlers_copy[i].apply(this, handlers_args);
}
// we do a copy so unbinds during a trigger don't corrupt the
// handler array
var catchall_copy = catch_all.slice(0);
var catchall_args = args.slice(0);
for(var i = 0, n = catchall_copy.length; i < n; i++) {
catchall_copy[i].apply(this, catchall_args);
}
return this;
}
});
Event._make_lookup_name = make_lookup_name;
Composer.exp0rt({ Event: Event });
}).apply((typeof exports != 'undefined') ? exports : this);
/**
* base.js
*
* Defines the base class for Composer objects (Model, Collection, etc)
* -----------------------------------------------------------------------------
*
* Composer.js is an MVC framework for creating and organizing javascript
* applications. For documentation, please visit:
*
* http://lyonbros.github.com/composer.js/
*
* -----------------------------------------------------------------------------
*
* Copyright (c) 2011, Lyon Bros LLC. (http://www.lyonbros.com)
*
* Licensed under The MIT License.
* Redistributions of files must retain the above copyright notice.
*/
(function() {
"use strict";
var Composer = this.Composer;
/**
* The base class is inherited by models, collections, and controllers. It
* provides some nice common functionality.
*/
var Base = Composer.Event.extend({
/**
* Track this object's type. Useful for debugging, mainly
*/
__composer_type: 'base',
/**
* Holds generic options for objects.
* */
options: {},
/**
* Every Composer object has an assigned unique id (regardless of the
* object's actual app ID). It is stored here.
*/
_cid: false,
/**
* CTOR, assigns our CID
*/
initialize: function() {
// assign the unique app id
this._cid = Composer.cid();
},
/**
* Pull out the object's unique Composer ID
*/
cid: function() {
return this._cid;
},
/**
* Convenience function to set options easily
*/
set_options: function(options) {
options || (options = {});
Object.keys(options).forEach(function(key) {
this.options[key] = options[key];
}.bind(this));
},
/**
* fire_event determines whether or not an event should fire. given an event
* name, the passed-in options, and any arbitrary number of arguments,
* determine whether or not the given event should be triggered.
*/
fire_event: function() {
var args = Array.prototype.slice.call(arguments, 0);
var evname = args.shift();
var options = args.shift();
options || (options = {});
// add event name back into the beginning of args
args.unshift(evname);
if(!options.silent && !options.not_silent) {
// not silent, fire the event
return this.trigger.apply(this, args);
} else if(
options.not_silent &&
(options.not_silent == evname ||
(options.not_silent.indexOf && options.not_silent.indexOf(evname) >= 0))
) {
// silent, BUT the given event is allowed. fire it.
return this.trigger.apply(this, args);
} else if(
options.silent &&
((typeof(options.silent) == 'string' && options.silent != evname) ||
(options.silent.indexOf && !(options.silent.indexOf(evname) >= 0)))
) {
// the current event is not marked to be silent, fire it
return this.trigger.apply(this, args);
}
return this;
}
});
Composer.exp0rt({ Base: Base });
}).apply((typeof exports != 'undefined') ? exports : this);
/**
* model.js
*
* Provides the data-driver layer of Composer
* -----------------------------------------------------------------------------
*
* Composer.js is an MVC framework for creating and organizing javascript
* applications. For documentation, please visit:
*
* http://lyonbros.github.com/composer.js/
*
* -----------------------------------------------------------------------------
*
* Copyright (c) 2011, Lyon Bros LLC. (http://www.lyonbros.com)
*
* Licensed under The MIT License.
* Redistributions of files must retain the above copyright notice.
*/
(function() {
"use strict";
var Composer = this.Composer;
/**
* Models are the data class. They deal with loading and manipulating data from
* various sources (ajax, local storage, etc). They make wrapping your actual
* data easy, and tie in well with collections/controllers via events to allow
* for easy updating and rendering.
*
* They also tie in with the Composer.sync function to provide a central place
* for saving/updating information with a server.
*/
var Model = Composer.Base.extend({
/**
* Track this object's type. Useful for debugging, mainly
*/
__composer_type: 'model',
// default values for the model, merged with the data passed in on CTOR
defaults: {},
// holds the model's data
data: {},
// whether or not the model has changed since the last save/update via sync
_changed: false,
// reference to the collections the model is in (yes, multiple). urls are
// pulled from the collection via a "priority" parameter. the highest
// priority collection will have its url passed to the model's sync function.
collections: [],
// what key to look under the data for the primary id for the object
id_key: 'id',
// DEPRECATED
// use this.url() instead
//
// can be used to manually set a base url for this model (in the case it
// doesn't have a collection or the url needs to change manually).
base_url: false,
// validation function, used to check data before it's set into the model
validate: function(data, options) { return false; },
/**
* CTOR, allows passing in of data to set that data into the model.
*/
initialize: function(data, options) {
data || (data = {});
var _data = {};
// merge in the defaults/data
var merge_fn = function(v, k) { _data[k] = v; };
Composer.object.each(Composer.object.clone(this.defaults), merge_fn);
Composer.object.each(data, merge_fn);
// call Base.initialize
this.parent();
// set the data into the model (but don't trigger any events)
this.set(_data, options);
// call the init fn
this.init(options);
},
/**
* override me, if needed
*/
init: function() {},
/**
* wrapper to get data out of the model. it's bad form to access model.data
* directly, you must always go through model.get('mykey')
*/
get: function(key, def) {
if(typeof(def) == 'undefined') def = null;
if(typeof(this.data[key]) == 'undefined') {
return def;
}
return this.data[key];
},
/**
* like Model.get(), but if the data is a string, escape it for HTML output.
*/
escape: function(key) {
var data = this.get(key);
if(data == null || typeof(data) != 'string') {
return data;
}
// taken directly from backbone.js's escapeHTML() function... thanks!
return data
.replace(/&(?!\w+;|#\d+;|#x[\da-f]+;)/gi, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/\//g,'/');
},
/**
* whether or not a key exists in this.data
*/
has: function(key) {
return this.data[key] != null;
},
/**
* set data into the model. triggers change events for individual attributes
* that change, and also a general change event if the model has changed. it
* only triggers these events if the model has indeed changed, setting an
* attribute to the same value it currently is will not trigger events:
*
* model.set({name: "fisty", age: 21});
*
* this will trigger the events:
* "change:name"
* "change:age"
* "change"
*
* if the model belongs to a collection, the events will bubble up to that
* collection as well, so as to notify the collection of any display changes
* needed.
*/
set: function(data, options) {
options || (options = {});
if(!options.silent && !this.perform_validation(data, options)) return false;
var already_changing = this.changing;
this.changing = true;
Composer.object.each(data, function(val, key) {
if(!Composer.eq(val, this.data[key])) {
this.data[key] = val;
this._changed = true;
this.fire_event('change:'+key, options, this, val, options);
}
}.bind(this));
if(!already_changing && this._changed) {
this.fire_event('change', options, this, options, data);
this._changed = false;
}
this.changing = false;
return this;
},
/**
* unset a key from the model's data, triggering change events if needed.
*/
unset: function(key, options) {
if(!(key in this.data)) return this;
options || (options = {});
var obj = {};
obj[key] = void(0);
if(!options.silent && !this.perform_validation(obj, options)) return false;
delete this.data[key];
this._changed = true;
this.fire_event('change:'+key, options, this, void 0, options);
this.fire_event('change', options, this, options);
this._changed = false;
return this;
},
/**
* Reset ALL data in the model with the given object. This function will
* fire change:* events for all added/removed/changed data (but not for
* data that remains the same).
*/
reset: function(data, options) {
options || (options = {});
if(!options.silent && !this.perform_validation(data, options)) return false;
var already_changing = this.changing;
this.changing = true;
var old = this.data;
// fire change for removed data
Composer.object.each(old, function(_, key) {
if(data.hasOwnProperty(key)) return;
delete this.data[key];
this._changed = true;
this.fire_event('change:'+key, options, this, void 0, options);
}.bind(this));
Composer.object.each(data, function(val, key) {
if(Composer.eq(val, old[key])) return;
this.data[key] = val;
this._changed = true;
this.fire_event('change:'+key, options, this, val, options);
}.bind(this));
if(!already_changing && this._changed) {
this.fire_event('change', options, this, options, data);
this._changed = false;
}
this.changing = false;
return this;
},
/**
* clear all data out of a model, triggering change events if needed.
*/
clear: function(options) {
options || (options = {});
var old = this.data;
var obj = {};
for(var key in old) obj[key] = void(0);
if(!options.silent && !this.perform_validation(obj, options)) return false;
this.data = {};
if(!options.silent) {
for(var key in old) {
this._changed = true;
this.fire_event('change'+key, options, this, void 0, options);
}
if(this._changed) {
this.fire_event('change', options, this, options);
this._changed = false;
}
}
return this;
},
/**
* fetch this model from the server, via its id.
*/
fetch: function(options) {
options || (options = {});
var success = options.success;
options.success = function(res) {
this.set(this.parse(res), options);
if(success) success(this, res);
}.bind(this);
options.error = Composer.wrap_error(options.error ? options.error.bind(this) : null, this, options).bind(this);
return (this.sync || Composer.sync).call(this, 'read', this, options);
},
/**
* save this model to the server (update if exists, add if doesn't exist (uses
* id to detemrine if exists or note).
*/
save: function(options) {
options || (options = {});
if(!this.perform_validation(this.data, options)) return false;
var success = options.success;
options.success = function(res) {
if(!this.set(this.parse(res), options)) return false;
if(success) success(this, res);
}.bind(this);
options.error = Composer.wrap_error(options.error ? options.error.bind(this) : null, this, options).bind(this);
return (this.sync || Composer.sync).call(this, (this.is_new() ? 'create' : 'update'), this, options);
},
/**
* delete this item from the server
*/
destroy: function(options) {
options || (options = {});
var success = options.success;
options.success = function(res) {
this.fire_event('destroy', options, this, this.collections, options);
if(success) success(this, res);
}.bind(this);
// if the model isn't saved yet, just mark it a success
if(this.is_new() && !options.force) return options.success();
options.error = Composer.wrap_error(options.error ? options.error.bind(this) : null, this, options).bind(this);