-
Notifications
You must be signed in to change notification settings - Fork 1
/
woodhouse.js
2558 lines (2111 loc) · 77.5 KB
/
woodhouse.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
(function(root, factory) {
"use strict";
// Set up Backbone appropriately for the environment. Start with AMD.
if (typeof define === 'function' && define.amd) {
define(['backbone', 'underscore', 'jquery'], function(Backbone, _, $) {
// Export global even in AMD case in case this script is loaded with
// others that may still expect a global.
root.Woodhouse = factory(root, Backbone, _, $);
});
} else {
root.Woodhouse = factory(root, root.Backbone, root._, (root.jQuery || root.$));
}
}(this, function(root, Backbone, _, $) {
"use strict";
// What is Woodhouse?
// ---
// Woodhouse is an extension to Backbone.
// Woodhouse adds the following things to Backbone:
// - View, Region, and Subview management (inspired by marionette.js)
// - Model-View bindings (inspired by knockout.js)
// - Model relations
// - Model computed properties
// - A better Router that aborts XHR requests when navigating
// Required dependencies
var missingDeps = [];
if (Backbone === undefined) {
missingDeps.push('Backbone');
}
if (_ === undefined) {
missingDeps.push('_');
}
if ($ === undefined) {
missingDeps.push('$');
}
if (missingDeps.length > 0) {
console.log("Warning! %s is undefined. Woodhouse aborted.", missingDeps.join(", "));
return;
}
// Define and export the Woodhouse namespace
var Woodhouse = {};
// Version string
Woodhouse.VERSION = '0.2.18';
// Debug flag
Woodhouse.DEBUG = false;
// Get jquery
Woodhouse.$ = $;
// Get lodash
Woodhouse._ = _;
// jQuery extensions
// ---
// Helper for inserting a child element at a specific index
$.fn.insertAt = function(index, element) {
var lastIndex = this.children()
.size();
if (index < 0) {
index = Math.max(0, lastIndex + 1 + index);
}
this.append(element);
if (index < lastIndex) {
this.children()
.eq(index)
.before(this.children()
.last());
}
return this;
};
// jQuery "splendid textinput" plugin
// http://benalpert.com/2013/06/18/a-near-perfect-oninput-shim-for-ie-8-and-9.html
// https://github.com/pandell/jquery-splendid-textchange
(function initSplendidTextChange($) {
// Determine if this is a modern browser (i.e. not IE 9 or older);
// if it is, the "input" event is exactly what we want so simply
// mirror it as "textchange" event
var testNode = document.createElement("input");
var isInputSupported = (testNode.oninput !== undefined &&
((document.documentMode || 100) > 9));
if (isInputSupported) {
$(document)
.on("input", function mirrorInputEvent(e) {
$(e.target)
.trigger("textchange");
});
return;
}
// ********* OLD IE (9 and older) *********
var queueEventTargetForNotification = null;
var activeElement = null;
var notificationQueue = [];
var watchedEvents = "keyup keydown";
// 90% of the time, keydown and keyup aren't necessary. IE 8 fails
// to fire propertychange on the first input event after setting
// `value` from a script and fires only keydown, keypress, keyup.
// Catching keyup usually gets it and catching keydown lets us fire
// an event for the first keystroke if user does a key repeat
// (it'll be a little delayed: right before the second keystroke).
// Return true if the specified element can generate
// change notifications (i.e. can be used by users to input values).
function hasInputCapabilities(elem) {
// The HTML5 spec lists many more types than `text` and `password` on
// which the input event is triggered but none of them exist in IE 8 or
// 9, so we don't check them here
return (
(elem.nodeName === "INPUT" &&
(elem.type === "text" || elem.type === "password")) ||
elem.nodeName === "TEXTAREA"
);
}
// Update the specified target so that we can track its value changes.
// Returns true if extensions were successfully installed, false otherwise.
function installValueExtensionsOn(target) {
if (target.valueExtensions) {
return true;
}
if (!hasInputCapabilities(target)) {
return false;
}
// add extensions container
// not setting "current" initially (to "target.value") allows
// drag & drop operations (from outside the control) to send change notifications
target.valueExtensions = {
current: null
};
// attempt to override "target.value" property
// so that it prevents "propertychange" event from firing
// (for consistency with "input" event behaviour)
if (target.constructor && target.constructor.prototype) { // target.constructor is undefined in quirks mode
var descriptor = Object.getOwnPropertyDescriptor(target.constructor.prototype, "value");
Object.defineProperty(target, "value", { // override once, never delete
get: function() {
return descriptor.get.call(this);
},
set: function(val) {
target.valueExtensions.current = val;
descriptor.set.call(this, val);
}
});
}
// subscribe once, never unsubcribe
$(target)
.on("propertychange", queueEventTargetForNotification)
.on("dragend", function onSplendidDragend(e) {
window.setTimeout(function onSplendidDragendDelayed() {
queueEventTargetForNotification(e);
}, 0);
});
return true;
}
// Fire "textchange" event for each queued element whose value changed.
function processNotificationQueue() {
// remember the current notification queue (for processing)
// + create a new queue so that if "textchange" event handlers
// cause new notification requests to be queued, they will be
// added to the new queue and handled in the next tick
var q = notificationQueue;
notificationQueue = [];
var target, targetValue, i, l;
for (i = 0, l = q.length; i < l; i += 1) {
target = q[i];
targetValue = target.value;
if (target.valueExtensions.current !== targetValue) {
target.valueExtensions.current = targetValue;
$(target)
.trigger("textchange");
}
}
}
// If target element of the specified event has not yet been
// queued for notification, queue it now.
queueEventTargetForNotification = function queueEventTargetForNotification(e) {
var target = e.target;
if (installValueExtensionsOn(target) && target.valueExtensions.current !== target.value) {
var i, l;
for (i = 0, l = notificationQueue.length; i < l; i += 1) {
if (notificationQueue[i] === target) {
break;
}
}
if (i >= l) { // "target" is not yet queued
notificationQueue.push(target);
if (l === 0) { // we just queued the first item, schedule processor in the next tick
window.setTimeout(processNotificationQueue, 0);
}
}
}
};
// Mark the specified target element as "active" and add event listeners to it.
function startWatching(target) {
activeElement = target;
$(activeElement)
.on(watchedEvents, queueEventTargetForNotification);
}
// Remove the event listeners from the "active" element and set "active" to null.
function stopWatching() {
if (activeElement) {
$(activeElement)
.off(watchedEvents, queueEventTargetForNotification);
activeElement = null;
}
}
// In IE 8, we can capture almost all .value changes by adding a
// propertychange handler (in "installValueExtensionsOn").
//
// In IE 9, propertychange/input fires for most input events but is buggy
// and doesn't fire when text is deleted, but conveniently,
// "selectionchange" appears to fire in all of the remaining cases so
// we catch those.
//
// In either case, we don't want to call the event handler if the
// value is changed from JS so we redefine a setter for `.value`
// that allows us to ignore those changes (in "installValueExtensionsOn").
$(document)
.on("focusin", function onSplendidFocusin(e) {
// stopWatching() should be a noop here but we call it just in
// case we missed a blur event somehow.
stopWatching();
if (installValueExtensionsOn(e.target)) {
startWatching(e.target);
}
})
.on("focusout", stopWatching)
.on("input", queueEventTargetForNotification)
.on("selectionchange", function onSplendidSelectionChange(e) {
// IE sets "e.target" to "document" in "onselectionchange"
// event (not very useful); use document.selection instead
// to determine actual target element
if (document.selection) {
var r = document.selection.createRange();
if (r) {
var p = r.parentElement();
if (p) {
e.target = p;
queueEventTargetForNotification(e);
}
}
}
});
}($));
// Javascript extensions
// ---
// Moves an array element from one index to another
Array.prototype.move = function(from, to) {
this.splice(to, 0, this.splice(from, 1)[0]);
};
// Woodhouse methods
// ---
// Log helper
Woodhouse.log = function() {
if (!Woodhouse.DEBUG || !console) {
return;
}
console.log.apply(console, arguments);
};
// Error Helper
Woodhouse.throwError = function(message, name) {
var error = new Error(message);
error.name = name || 'Error';
throw error;
};
// Centralized XHR pool
// Allows automatic aborting of pending XHRs when navigate is called
Woodhouse.xhrs = [];
Woodhouse.addXhr = function(xhr) {
// Invalid xhr (or false)
// Backbone sync will may return false
if (!xhr) {
return;
}
Woodhouse.xhrs.push(xhr);
xhr.always(function() {
var index = _.indexOf(Woodhouse.xhrs, this);
if (index >= 0) {
Woodhouse.xhrs.splice(index, 1);
}
}.bind(xhr));
};
// Woodhouse.Router
// ---
// Extends Backbone.Router
Woodhouse.Router = Backbone.Router.extend({
navigate: function(route, options) {
options = options || {};
// Don't navigate if route didn't change
if (Backbone.history.fragment === route) {
return this;
}
// Determine whether we should navigate
if (!this.shouldNavigate(options)) {
return this;
}
// This aborts all pending XHRs when Backbone tries to navigate
_.each(Woodhouse.xhrs, function(xhr) {
if (xhr.readyState && xhr.readyState > 0 && xhr.readyState < 4) {
Woodhouse.log('XHR aborted due to router navigation');
xhr.abort();
}
});
Woodhouse.xhrs = [];
if (options.force) {
Backbone.history.fragment = null;
}
Backbone.history.navigate(route, options);
},
shouldNavigate: function(options) {
return true;
},
});
// Computed Properties
Function.prototype.property = function() {
var args = Array.prototype.slice.call(arguments);
this.properties = args;
return this;
};
// Woodhouse.Model
// ---
// Extends Backbone.DeepModel and adds support for:
// Backbone.Model.oldset = Backbone.Model.prototype.set;
//
// - relations
// - computed properties
Woodhouse.Model = Backbone.Model.extend({
constructor: function(attributes, options) {
var attrs = attributes || {};
options || (options = {});
this.cid = _.uniqueId('c');
this.attributes = {};
if (options.collection) this.collection = options.collection;
if (options.parse) attrs = this.parse(attrs, options) || {};
attrs = _.defaults({}, attrs, _.result(this, 'defaults'));
// Automatically create empty relations
if (this.relations) {
_.each(this.relations, function(relation) {
if (!_.has(attrs, relation.key)) {
attrs[relation.key] = relation.type === 'model' ? {} : [];
}
}.bind(this));
}
this.set(attrs, options);
this.changed = {};
this.initialize.apply(this, arguments);
},
// Tested and working with both shallow and deep keypaths
get: function(attr) {
if (!_.isString(attr)) {
return undefined;
}
return this.getDeep(this.attributes, attr);
},
getDeep: function(attrs, attr) {
var keys = attr.split('.');
var isModel, isCollection;
var key;
var val = attrs;
var context = this;
for (var i = 0, n = keys.length; i < n; i++) {
// determine if ??? is backbone model or collection
isModel = val instanceof Backbone.Model;
isCollection = val instanceof Backbone.Collection;
// get key
key = keys[i];
// Hold reference to the context when diving deep into nested keys
if (i > 0) {
context = val;
}
// get value for key
if (isCollection) {
val = val.models[key];
} else if (isModel) {
val = val.attributes[key];
} else {
val = val[key];
}
// value for key does not exist
// break out of loop early
if (_.isUndefined(val) || _.isNull(val)) {
break;
}
}
// Eval computed properties that are functions
if (_.isFunction(val)) {
// Call it with the proper context (see above)
val = val.call(context);
}
return val;
},
// Custom modified Backbone.Model.set to support relations
set: function(key, val, options) {
var attr, attrs, unset, changes, silent, changing, prev, current;
if (_.isUndefined(key) || _.isNull(key)) {
return this;
}
// Handle both `"key", value` and `{key: value}` -style arguments.
if (typeof key === 'object') {
attrs = key;
options = val;
} else {
(attrs = {})[key] = val;
}
options || (options = {});
// Run validation.
if (!this._validate(attrs, options)) return false;
// Extract attributes and options.
unset = options.unset;
silent = options.silent;
changes = [];
changing = this._changing;
this._changing = true;
if (!changing) {
this._previousAttributes = this.deepClone(this.attributes);
this.changed = {};
}
current = this.attributes, prev = this._previousAttributes;
// Check for changes of `id`.
if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
// For each `set` attribute, update or delete the current value.
for (attr in attrs) {
val = attrs[attr];
if (!this.compareAttribute(current, attr, val)) {
changes.push(attr);
// Add any nested object key changes
if (_.isObject(val) && !_.isArray(val)) {
var nestedChanges = _.keys(this.objToPaths(val));
_.each(nestedChanges, function(nestedChange) {
changes.push(attr + '.' + nestedChange);
});
}
}
if (!this.compareAttribute(prev, attr, val)) {
this.setAttribute(this.changed, attr, val, {
changed: true
});
} else {
this.unsetAttribute(this.changed, attr);
}
unset ? this.unsetAttribute(current, attr) : this.setAttribute(current, attr, val, {});
}
// Trigger all relevant attribute changes.
var alreadyTriggered = {};
if (!silent) {
if (changes.length) this._pending = options;
for (var i = 0, l = changes.length; i < l; i++) {
if (!_.has(alreadyTriggered, changes[i])) {
this.trigger('change:' + changes[i], this, this.getDeep(current, changes[i]), options);
Woodhouse.log("model.%s set.trigger -> change:%s -> %s", this.cid, changes[i], JSON.stringify(this.getDeep(current, changes[i])));
alreadyTriggered[changes[i]] = true;
}
// Trigger change events for parent keys with wildcard (*) notation
var keys = changes[i].split('.');
for (var n = keys.length - 1; n > 0; n--) {
var parentKey = _.first(keys, n).join('.');
var wildcardKey = parentKey + '.' + '*';
if (!_.has(alreadyTriggered, wildcardKey)) {
this.trigger('change:' + wildcardKey, this, this.getDeep(current, parentKey), options);
Woodhouse.log("model.%s set.trigger -> change:%s -> %s", this.cid, wildcardKey, JSON.stringify(this.getDeep(current, parentKey)));
alreadyTriggered[wildcardKey] = true;
}
}
}
}
// Computed properties
this.computedPropertyEvents(attrs);
// You might be wondering why there's a `while` loop here. Changes can
// be recursively nested within `"change"` events.
if (changing) return this;
if (!silent) {
while (this._pending) {
options = this._pending;
this._pending = false;
this.trigger('change', this, options);
Woodhouse.log("model.%s set.trigger -> change", this.cid);
}
}
this._pending = false;
this._changing = false;
return this;
},
objToPaths: function(obj) {
var ret = {};
var separator = '.';
_.each(obj, function(val, key) {
if (_.isObject(val) && !_.isArray(val) && !_.isEmpty(val)) {
//Recursion for embedded objects
var obj2 = this.objToPaths(val);
for (var key2 in obj2) {
var val2 = obj2[key2];
ret[key + separator + key2] = val2;
}
} else {
ret[key] = val;
}
}.bind(this));
return ret;
},
unflattenAttribute: function(attr, attrs) {
var keys = attr.split('.');
if (keys.length > 1) {
var obj = {};
var result = obj;
for (var i = 0, n = keys.length; i < n; i++) {
var key = keys[i];
if (i === n - 1) {
result[keys[i]] = attrs[attr];
} else {
//Create the child object if it doesn't exist, or isn't an object
if (typeof result[key] === 'undefined' || !_.isObject(result[key])) {
var nextKey = keys[i + 1];
// create array if next key is integer, else create object
result[key] = /^\d+$/.test(nextKey) ? [] : {};
}
//Move onto the next part of the path
result = result[key];
}
}
delete attrs[attr];
_.extend(attrs, obj);
return _.first(keys);
}
return attr;
},
compareAttribute: function(attrs, attr, val) {
var oldVal = this.getDeep(attrs, attr);
if (oldVal instanceof Backbone.Model) {
oldVal = oldVal.attributes;
} else if (oldVal instanceof Backbone.Collection) {
oldVal = oldVal.models;
}
return _.isEqual(oldVal, val);
},
setAttribute: function(attrs, attr, val, options) {
var keys = attr.split('.');
var key;
var result = attrs;
var context = this;
var relation;
for (var i = 0, n = keys.length; i < n; i++) {
// Hold reference to the context when diving deep into nested keys
if (i > 0) {
context = result;
}
// get key
key = keys[i];
// Look for a potential relation
if (!options.changed && context.relations) {
relation = _.findWhere(context.relations, {
key: key
});
} else {
relation = null;
}
// If the current root is a backbone model
// The next level is under attributes
if (result.attributes) {
result = result.attributes;
} else if (result.models) {
result = result.models;
}
// last key
if (i === n - 1) {
if (relation && relation.type === 'model') {
if (val.attributes) {
val = val.attributes;
}
if (!(result[key] instanceof relation.model)) {
result[key] = new relation.model(val);
} else {
result[key].set(val);
// result[key].attributes = val;
}
} else if (relation && relation.type === 'collection') {
if (val.models) {
val = val.models;
}
if (!(result[key] instanceof relation.collection)) {
result[key] = new relation.collection(val);
} else {
result[key].reset(val);
}
} else {
if (result[key] && _.isFunction(result[key].set)) {
result[key].set(val);
} else {
result[key] = val;
}
}
} else { // not last key
// if key is undefined and relation exists, create an empty model
// if key is undefined and no relation exists, create an empty object
if (_.isUndefined(result[key]) || _.isNull(result[key])) {
result[key] = relation ? new relation.model() : {};
}
// dive another level
result = result[key];
}
}
},
unsetAttribute: function(attrs, attr) {
var isModel, isCollection;
var keys = attr.split('.');
var key;
var val = attrs;
var isLastKey = false;
for (var i = 0, n = keys.length; i < n; i++) {
isModel = val instanceof Backbone.Model;
isCollection = val instanceof Backbone.Collection;
key = keys[i];
if (i === n - 1) {
isLastKey = true;
}
if (isCollection) {
if (isLastKey) {
val.remove(val.models[key]);
} else {
val = val.models[key];
}
} else if (isModel) {
if (isLastKey) {
delete val.attributes[key];
} else {
val = val.attributes[key];
}
} else {
if (isLastKey) {
delete val[key];
} else {
val = val[key];
}
}
// value for key does not exist
// break out of loop early
if (_.isUndefined(val) || _.isNull(val)) {
break;
}
}
},
hasChanged: function(attr) {
if (_.isUndefined(attr) || _.isNull(attr)) {
return !_.isEmpty(this.changed);
}
return !_.isUndefined(this.getDeep(this.changed, attr));
},
changedAttributes: function(diff) {
if (!diff) return this.hasChanged() ? this.deepClone(this.changed) : false;
var val, changed = false;
var old = this._changing ? this._previousAttributes : this.attributes;
for (var attr in diff) {
if (_.isEqual(old[attr], (val = diff[attr]))) continue;
(changed || (changed = {}))[attr] = val;
}
return changed;
},
// Get the previous value of an attribute, recorded at the time the last
// `"change"` event was fired.
previous: function(attr) {
if (_.isUndefined(attr) || _.isNull(attr) || !this._previousAttributes) {
return null;
}
return this.getDeep(this._previousAttributes, attr);
},
// Get all of the attributes of the model at the time of the previous
// `"change"` event.
previousAttributes: function() {
return this.deepClone(this._previousAttributes);
},
// Attach event listeners to the raw properties of the computed property
computedPropertyEvents: function(attrs) {
var attr;
for (attr in attrs) {
var events = "";
var val = attrs[attr];
if (!_.isFunction(val)) {
continue;
}
_.each(val.properties, function(property) {
var key = attr;
var fn = val;
var entity = this.get(property);
if (entity instanceof Backbone.Collection) {
events = "change reset add remove sort";
} else if (entity instanceof Backbone.Model) {
events = "change";
} else {
entity = this;
events = "change:" + property;
}
this.listenTo(entity, events, function() {
var value = fn.call(this);
this.trigger('change:' + key, this, value);
}.bind(this));
}.bind(this));
}
},
// Borrowed from backbone-deep-model
deepClone: function(obj) {
var func, isArr;
if (!_.isObject(obj) || _.isFunction(obj)) {
return obj;
}
if (obj instanceof Backbone.Collection || obj instanceof Backbone.Model) {
return obj;
}
if (_.isDate(obj)) {
return new Date(obj.getTime());
}
if (_.isRegExp(obj)) {
return new RegExp(obj.source, obj.toString().replace(/.*\//, ""));
}
isArr = _.isArray(obj || _.isArguments(obj));
func = function(memo, value, key) {
if (isArr) {
memo.push(this.deepClone(value));
} else {
memo[key] = this.deepClone(value);
}
return memo;
}.bind(this);
return _.reduce(obj, func, isArr ? [] : {});
},
// Override toJSON to support relations and computed properties
toJSON: function(options) {
var json = this.deepClone(this.attributes);
// Convert all relations from models/collections to objects/arrays
if (this.relations) {
_.each(this.relations, function(relation) {
var object;
// Look for embedded relations
if (_.has(json, relation.key)) {
// If the value is a model or collection and has a toJSON function
if (json[relation.key] instanceof Backbone.Model || json[relation.key] instanceof Backbone.Collection) {
json[relation.key] = json[relation.key].toJSON(options);
}
} else {
if (relation.type === 'collection') {
json[relation.key] = [];
} else if (relation.type === 'model') {
json[relation.key] = {};
}
}
}.bind(this));
}
// Remove computed properties from output
_.each(json, function(val, key) {
if (_.isFunction(val)) {
delete json[key];
}
});
return json;
}
});
// Woodhouse.Model
// ---
// Extends Backbone.Collection and sets default model class to Woodhouse.Model
Woodhouse.Collection = Backbone.Collection.extend({
model: Woodhouse.Model,
// Proxy for Array's move method and also fires a `sort` event
move: function() {
Array.prototype.move.apply(this.models, arguments);
this.trigger('sort', this);
return this;
}
});
// Woodhouse.Region
// ---
//
// This is like a UIViewController
// It has a property `view` that is shown in the DOM at location of the property `el`
// If the region is closed via the `close` method, the `view` will be removed by calling it's `remove` method
// If a region shows a view and an existing different view is currently being shown, it will be closed
//
// Instance Options/Attributes
// Prototype Properties and Methods
// onBeforeShow
// onShow
// onBeforeClose
// onClose
Woodhouse.Region = function(options) {
this.cid = _.uniqueId('region');
options = options || {};
_.extend(this, _.pick(options, ['el']));
if (!this.el) {
var err = new Error("An 'el' must be specified for a region.");
err.name = "NoElError";
throw err;
}
this.ensureEl();
this.initialize.apply(this, arguments);
};
// Allow Woodhouse.Region to be extendable like Backbone.View
Woodhouse.Region.extend = Backbone.View.extend;
// Add methods to the prototype of Woodhouse.Region
_.extend(Woodhouse.Region.prototype, Backbone.Events, {
initialize: function() {},
// Converts el to $el using the DOM manipulator
ensureEl: function() {
if (!this.$el || this.$el.length === 0) {
this.$el = Woodhouse.$(this.el);
}
},
// Determines if the region is showing a view or not
isShowing: function() {
return this.view ? true : false;
},
// Show a view in the region
// This will replace any previous view shown in the region
// options - object
// render - boolean - default true, whether the view should be rendered after show
show: function(view, options) {
options = options || {};
_.defaults(options, {
render: true
});
// Remove previous view if the new view is different by closing region
if (this.view && this.view !== view) {
this.close();
}
// Set current view
this.view = view;
// Set the view's region
view.region = this;
// This method gets called BEFORE show
if (_.isFunction(this.onBeforeShow)) {
this.onBeforeShow();
}
// Append the view DOM el into the region at the DOM location specified by `el`
this.$el.empty()
.append(view.el);
// Render the view
if (options.render) {
view.render.call(view);
}
// This method gets called AFTER show
if (_.isFunction(this.onShow)) {
this.onShow();
}
return this;
},
// Remove the current view in the region
close: function() {
// This method gets called BEFORE close
if (_.isFunction(this.onBeforeClose)) {
this.onBeforeClose();
}
// Remove the view and null it
if (this.view) {
this.view.remove.call(this.view);
}
this.view = null;