-
Notifications
You must be signed in to change notification settings - Fork 1
/
backbone.rebar.js
1198 lines (1193 loc) · 42.2 KB
/
backbone.rebar.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(Backbone, _, $) {
'use strict';
/**
* @namespace Rebar
*/
var Rebar = this.Rebar = Backbone.Rebar = {};
// =======================================================================
// === Pollyfills ========================================================
// =======================================================================
// @TODO work in ability to use two args
if (!Object.create) {
Object.create = function(o) {
if (arguments.length > 1) {
throw new Error('Object.create implementation only accepts the first parameter.');
}
function F() {}
F.prototype = o;
return new F();
};
}
// =======================================================================
// === Helpers ===========================================================
// =======================================================================
/**
* Extention functionality for the prototyped object that implements it.
* @method extend
* @param {Object} protoProps
* @return {Object} child
*/
var extend = function(protoProps) {
var parent = this;
var child = function() {
parent.apply(this, arguments);
};
child.prototype = _.extend(parent.prototype, protoProps);
return child;
};
// =======================================================================
// === Application =======================================================
// =======================================================================
/**
* The application shell provides a simple default architecture consisting of a model,
* view and controller. The application is a singleton class in that there can only be one.
* It extends `Backbone.Events` and you can see the [documentation](http://backbonejs.org/#Events)
* for more detailed information.
* @class Application
* @constructor
* @extends Backbone.Events
* @uses extend
* @example
* var appConfig = {
* ...
* };
* var app = new Backbone.Rebar.Application(appConfig);
* app.on("applicationStateChange",function(state){
* ...
* });
* app.startup();
*/
var Application = Rebar.Application = function(options) {
// singleton functionality
if (Application.instance && options && !options._bypassSingleton) {
return Application.instance;
}
if (options && options.logLevel) {
Logger.setLogLevel(options.logLevel);
} else {
Logger.setLogLevel(Logger.Levels.None);
}
Application.instance = this;
this.options = options ? options : {};
this.state = Application.States.Initialized;
// setup listener for app shutdown
$(window).on('beforeunload unload', $.proxy(function(e) {
this.state = Application.States.Shutdown;
}, this));
};
/**
* Available states for the application used to describe the current state of the Application.
* @property States
* @type Object
* @for Application
* @final
*/
Application.States = {
Default: 0,
Initialized: 1,
Faulted: 2,
Started: 3,
Shutdown: 4
};
Application.prototype = Object.create(Backbone.Events, {
/**
* The current state value.
* @property _state
* @type Integer
* @for Application
* @private
*/
_state: {
value: Application.States.Default,
writable: true
},
/**
* Getters and setters for the current state value.
* @property state
* @type Integer
* @for Application
*/
state: {
get: function() {
return this._state;
},
set: function(state) {
if (this._state === state) {
return;
}
this._state = state;
if (this._state === Application.States.Initialized) {
if (_.isFunction(this.createModel)) {
this.createModel(this.options.modelOptions);
}
if (_.isFunction(this.createController)) {
this.createController(this.options.controllerOptions);
}
if (_.isFunction(this.createView)) {
this.createView(this.options.viewOptions);
}
if (_.isFunction(this.createRouter)) {
this.createRouter(this.options.routerOptions);
}
this.initialize(this.options);
}
this.trigger('applicationStateDidChange', this.state);
}
},
/**
* Initialization functionality for extended Application instances.
* @method initialize
* @for Application
*/
initialize: {
value: function(options) {},
writable: true
},
/**
* Create a model instance for the Application instance.
* @method createModel
* @for Application
*/
createModel: {
value: function(modelOptions) {
if (!this.model) {
this.model = new Backbone.Model(_.extend({}, modelOptions));
}
},
writable: true
},
/**
* Create a view instance for the Application instance.
* @method createView
* @for Application
*/
createView: {
value: function(viewOptions) {
if (!this.view) {
this.view = new CompositeView(_.extend({
el: $('#application'),
model: this.model,
controller: this.controller
}, viewOptions));
}
},
writable: true
},
/**
* Create a controller instance for the Application instance.
* @method createController
* @for Application
*/
createController: {
value: function(controllerOptions) {
if (!this.controller) {
this.controller = new Controller(_.extend({
model: this.model
}, controllerOptions));
}
},
writable: true
},
/**
* Create a dependency router instance for the Application instance.
* @method createRouter
* @for Application
*/
createRouter: {
value: function(routerOptions) {
if (!this.router) {
this.router = new DependencyRouter(_.extend({
landing: this.options.landing ? this.options.landing : '',
dispatcher: this
}, routerOptions));
this.router.on('routeDidChange', function(route) {
this.trigger('routeDidChange', route);
}, this);
}
},
writable: true
},
/**
* This method kicks off Backbone's history management as well as loads the bootstrap data
* if a reference was passed through the constructors options argument.
* @method startup
* @for Application
*/
startup: {
value: function() {
if (this.options.bootstrap) {
var delegate = this;
$.ajax({
cache: false,
dataType: 'json',
type: 'GET',
url: this.options.bootstrap,
success: function(response) {
if (!_.isEmpty(response)) {
delegate.model.set('bootstrap', response);
Backbone.history.start({
pushState: false
});
delegate.state = Application.States.Started;
} else {
delegate.error = 'Error: Bootstrap load error.';
delegate.state = Application.States.Faulted;
}
},
error: function(error) {
delegate.error = error;
delegate.state = Application.States.Faulted;
}
});
} else {
Backbone.history.start({
pushState: false
});
this.state = Application.States.Started;
}
}
}
});
Application.extend = extend;
// =======================================================================
// === Persistence Model =================================================
// =======================================================================
/**
* The `PeristenceModel` extends the basic [Backbone.Model](http://backbonejs.org/#Model)
* and overwrites its sync method to take advantage of local storage and persist data
* across multiple pages within the same domain. The url property is used to grab data
* from a specific object of the localStorage object. Use the `fetch` method to pull
* whatever data already exists in localStorage and use the `save` method to store for
* later use.
* @class PersistenceModel
* @extends Backbone.Model
* @constructor
* @example
* var model = new Backbone.Rebar.PersistenceModel({
* url:"custom"
* });
* model.fetch();
* model.set("foo","bar");
* model.save();
*/
var PersistenceModel = Rebar.PersistenceModel = Backbone.Model.extend({
/**
* Determains and returns a storage id based on the passed id in initialization
* @method getStoargeId
* @return {String} storage id for this persistence model
* @private
*/
getStoargeId: function() {
var id = 'pm';
if (this.urlRoot) {
// for right now lets just keep this simple
// @TODO: support ids with urlRoots
id = id + '_' + this.url().split('/')[0];
}
return id;
},
/**
* Overriden to make sure that we have a urlRoot on our persistence model
* @method set
* @param {Object} key
* @param {Object} val
* @param {Object} options
*/
set: function(key, val, options) {
if (key === 'url') {
this.urlRoot = val;
} else if (_.isObject(key) && _.has(key, 'url') && !_.isUndefined(key.url)) {
this.urlRoot = key.url;
}
Backbone.Model.prototype.set.call(this, key, val, options);
},
/**
* Overridden to reroute the to a localStorage endpoint.
* @method sync
* @param {String} method
* @param {PersistenceModel} model
* @param {Object} options
* @private
*/
sync: function(method, model, options) {
if (method === 'read') {
try {
this.pullLocalStore(model, options);
} catch (e) {
console.error("Error reading from local store " + model.getStoargeId(), e);
}
} else if (method === 'create') {
var item;
try {
var filteredObj = _.omit(model.attributes, ['url', 'urlRoot']);
item = JSON.stringify(filteredObj);
} catch (e) {
console.error("Error writing item to local store " + model.getStoargeId(), e);
}
localStorage.setItem(model.getStoargeId(), item);
} else if (method === 'update') {
try {
this.pullLocalStore(model, options);
} catch (e) {
console.error("Error updating model from local store " + model.getStoargeId(), e);
}
} else if (method === 'patch') {
throw '\'patch\' not implemented yet';
} else if (method === 'delete') {
throw '\'delete\' not implemented yet';
}
},
/**
* Helper method pulls data based on urlRoot from local storage
* @method pullLocalStore
* @param {PersistenceModel} model
* @param {Object} options
* @private
*/
pullLocalStore: function(model, options) {
if (localStorage) {
var data = localStorage.getItem(model.getStoargeId());
if (data !== null) {
var parsedData = JSON.parse(data);
model.set(parsedData);
// @TODO: Do i need the following 3 lines anymore ???
//if (options.success) {
// options.success(model, parsedData, options);
//}
model.trigger('sync', model, parsedData, options);
}
} else {
var error = 'Error: \'localStorage\' is not supported';
if (options.error) {
options.error(model, error, options);
}
model.trigger('sync', model, error, options);
}
}
});
// =======================================================================
// === View ==============================================================
// =======================================================================
/**
* Base class that extends [Backbone.View](http://backbonejs.org/#View) and
* provides boilerplate plate functionality for transitioning in and out, destroying
* and rendering views.
* @class View
* @constructor
* @extends Backbone.View
* @example
* var view = new Backbone.Rebar.View({
* ...
* });
* view.transitionIn({
* ...
* });
* view.transitionOut({
* this.destroy();
* },this);
*/
var View = Rebar.View = function(options) {
Backbone.View.call(this, options);
_.extend(this, _.pick(this.options, ['render', 'destroy', 'transitionIn', 'transitionOut', 'controller']));
};
View.prototype = Object.create(Backbone.View.prototype, {
/**
* isDestroyed getter
* @property isDestroyed
* @type Boolean
*/
isDestroyed: {
get: function() {
return _.isUndefined(this._isDestroyed) ? false : this._isDestroyed;
}
},
/**
* Reference to the views controller
* @property controller
* @type Controller
*/
controller: {
value: undefined,
writable: true
},
/**
* This method is a great helper method to call when the subclass view is about to be removed.
* It recursively will call destroy on any subviews reference in the sub views array. It also handles
* removing any event listeners that may have been added to the subViews array.
* @method destroy
*/
destroy: {
value: function() {
if (!this._isDestroyed) {
this._isDestroyed = true;
this.trigger('viewDidDestroy', this);
this.off();
this.$el.off();
this.remove();
}
},
writable: true
},
/**
* For instances that are used in dependency routing the render method is called
* and used directly after loading. For all other uses you must call render manually.
* @method render
* @param {Function} callback
*/
render: {
value: function(callback) {
// ...
},
writable: true
},
/**
* Transitions in the view. By default this method actually does nothing.
* @method transitionIn
* @param {Function} callback
*/
transitionIn: {
value: function(callback, context) {
if (_.isFunction(callback)) {
callback.call(context ? context : this);
}
},
writable: true
},
/**
* Transitions out the view. By default this method actually does nothing.
* @method transitionOut
* @param {Function} callback
*/
transitionOut: {
value: function(callback, context) {
if (_.isFunction(callback)) {
callback.call(context ? context : this);
}
},
writable: true
}
});
View.extend = Backbone.View.extend;
// =======================================================================
// === Composite View ====================================================
// =======================================================================
/**
* Most of the time Backbone views need to be able to contain other views. When you do this you run
* into situations where you need to add the view then render and when you go to destroy the parent
* view, you want to make sure you properly dispose of its children.
* The composite view makes managing child parent relationships a bit easier by adding recursive destroy
* functionality as well as making it possible to quickly add and remove child views.
* @class CompositeView
* @extends View
* @constructor
* @example
* var composite = new Backbone.Rebar.CompositeView({
* ...
* });
* var view = new Backbone.Rebar.View({
* ...
* });
* composite.addSubView(view);
*/
var CompositeView = Rebar.CompositeView = function(options) {
this.subViews = [];
View.call(this, options);
//_.extend(this, _.pick(this.options, ['addSubView', 'removeSubView', 'removeAllSubViews', 'destroy']));
};
CompositeView.prototype = Object.create(View.prototype, {
/**
* Adds a sub view to a container BaseView
* @method addSubView
* @param {View} view
*/
addSubView: {
value: function(view) {
// add event listeners for view
view.on('viewDidDestroy', function(view) {
this.removeSubView(view);
}, this);
// add sub view
this.subViews.push(view);
// render subview
var delegate = this;
view.render(function(el) {
var markup = el ? el : view.el;
delegate.$el.append(markup);
});
// @TODO - possibly trigger view has been added
},
writable: true
},
/**
* Adds an array of sub views to a container BaseView
* @method addSubViews
* @param {Array} views Array of subviews
*/
addSubViews: {
value: function(views) {
_.each(views, function(view) {
this.addSubView(view);
}, this);
},
writable: true
},
/**
* Removes a sub view from the container view
* @method removeSubView
* @param {Object} view A base view or a cid of the sub view
*/
removeSubView: {
value: function(view) {
// assuming that what was passed was not an actual view and in fact was a cid
if (!view.cid) {
view = _.where(this.subViews, {
cid: view
})[0];
}
this.destroySubView(view);
this.subViews = _.reject(this.subViews, function(subView) {
return subView.cid === view.cid;
});
},
writable: true
},
/**
* Removes all sub views from view
* @method removeAllSubViews
*/
removeAllSubViews: {
value: function() {
_.each(this.subViews, function(view) {
this.removeSubView(view);
}, this);
},
writable: true
},
/**
* This method is a great helper method to call when the subclass view is about to be removed.
* It recursively will call destroy on any subviews reference in the sub views array. It also handles
* removing any event listeners that may have been added to the subViews array.
* @method destroy
*/
destroy: {
value: function() {
// recursively destroy sub views
if (this.subViews.length > 0) {
_.each(this.subViews, function(view) {
this.destroySubView(view);
}, this);
}
this.subViews = [];
View.prototype.destroy.call(this);
},
writable: true
},
/**
* Checks to see if the passed view has destroy functionality and then if it does not
* calls the prototype destroy functionality and passes the reference
* @method destroySubView
* @param {View} view
* @private
*/
destroySubView: {
value: function(view) {
if (_.isFunction(view.destroy) && !view.isDestroyed) {
view.destroy(true);
} else {
if (!_.isUndefined(view.cid)) {
View.prototype.destroy.call(view);
}
}
},
writable: true
}
});
CompositeView.extend = View.extend;
// =======================================================================
// === Mediator ==========================================================
// =======================================================================
/**
* Simple implementation of the [mediator pattern](http://en.wikipedia.org/wiki/Mediator_pattern) for use with Backbone.Views
* @class Mediator
* @constructor
* @uses extend
* @example
* var mediator = new Mediator({
* events:{
* "appwide1":{
* dispatcher:app
* callback:"method"
* }
* },
* initialize:function(options){
* ...
* },
* method:function(e){
* ...
* },
* handle:function(eventName,module){
* ...
* }
* });
* mediator.addView(view,"event1 event2");
* view.trigger("something",view);
* mediator.removeView(view);
*/
var Mediator = Rebar.Mediator = function(options) {
if (options) {
this.options = options;
_.extend(this, _.pick(this.options, ['initialize', 'handle', 'view']));
if (this.options.events) {
this.processEvents(this.options.events);
}
if (this.view && this.options.viewEvents) {
this.processViewEvents(this.options.viewEvents);
}
}
this._views = [];
this.initialize(options);
};
Mediator.prototype = Object.create(Backbone.Events, {
/**
* Stores reference to all views added to the mediator.
* @property _views
* @type Array
* @for Mediator
* @private
*/
_views: {
value: undefined,
writable: true,
configurable: false
},
/**
* Reference to a single view who we'll be mediating for.
* @property view
* @type Backbone.View
* @for Mediator
*/
view: {
value: undefined,
writable: true,
configurable: false
},
/**
* Called for any modules that extend the `Mediator` prototype.
* @method initialize
* @for Mediator
*/
initialize: {
value: function(options) {},
writable: true
},
/**
* Adds module as one that the mediator should be listening for events.
* @method addView
* @for Mediator
* @param {Backbone.View} view
* @param {String} eventNames
*/
addView: {
value: function(view, eventNames) {
var events;
if (eventNames) {
events = eventNames.split(' ');
} else {
events = ['all'];
}
_.each(events, function(eventName) {
view.on(eventName, function(options) {
this.handle(eventName, view, options);
}, this);
}, this);
this._views.push(view);
},
writable: true
},
/**
* Removes module from one that the mediator should be listening for.
* @method removeView
* @for Mediator
* @param {Backbone.View} view
*/
removeView: {
value: function(view) {
// @TODO: remove all events that the view has with this handler
view.off(null, this.handle, this);
this._views = _.reject(this._views, function(v) {
if (v.cid === view.cid) {
return true;
}
return false;
}, this);
},
writable: true
},
/**
* Returns boolean for whether the mediator contains a view or not.
* @method hasView
* @for Mediator
* @param {Backbone.View} view
*/
hasView: {
value: function(view) {
return _.where(this._views, {
cid: view.cid
})[0];
},
writable: true
},
/**
* Returns a view that has the same value/key pairs provided
* @method getView
* @for Mediator
* @param {Object} attribute Key/Value pair to use with an UnderscoreJS _.with look up
* @example
* ...
* mediator.getView({name:"foo"});
*/
getView: {
value: function(attribute) {
return _.filter(this._views, function(view) {
var key = _.keys(attribute)[0];
var value = _.values(attribute)[0];
if (view[key] && view[key] === value) {
return true;
} else if (view.options && view.options[key] && view.options[key] === value) {
return true;
}
return false;
})[0];
},
writable: true
},
/**
* Returns a view that has the same **user defined** name provided
* @method getViewByName
* @for Mediator
* @param {String} name User defined view name
* @example
* ...
* mediator.getView({name:"foo"});
*/
getViewByName: {
value: function(name) {
var view = this.getView({
name: name
});
if (_.isUndefined(view)) {
console.warn('Property \'name\' was not found on any views.');
}
return view;
},
writable: true
},
/**
* destroys a mediator and removes all listeners.
* @method destroy
* @for Mediator
*/
destroy: {
value: function() {
_.each(this._views, function(view) {
this.removeView(view);
}, this);
},
writable: true
},
/**
* Handler method that is called when one of the module the mediator is listening
* for is fired. Should be overwritten in `Mediator` instances.
* @method handle
* @for Mediator
* @param {Object} eventName
* @param {Object} module
*/
handle: {
value: function(eventName, view) {},
writable: true
},
/**
* Runs through all of the events that the mediator should be listening for.
* @method processEvents
* @for Mediator
* @param {Object} events
* @private
*/
processEvents: {
value: function(events) {
for (var item in events) {
var eventObj = events[item];
if (_.isObject(eventObj)) {
this.assignCallbackToDispatcher(item, eventObj.callback, eventObj.dispatcher);
} else {
this.assignCallbackToDispatcher(item, eventObj, this.options.dispatcher);
}
}
}
},
/**
* Processes all of the viewEvents passes in through the mediator config options
* @method processViewEvents
* @for Mediator
* @param {String} events
* @private
*/
processViewEvents: {
value: function(events) {
var eventsArr = events.split(" ");
_.each(eventsArr, function(event, index) {
this.view.on(event.toString(), function(options) {
this.handle(event, this.view, options);
}, this);
}, this);
}
},
/**
* Assigns a callback to the passed dispatcher for the event to be fired.
* @method assignCallbackToDispatcher
* @for Mediator
* @param {String} eventName
* @param {String} callbackName
* @param {Object} dispatcher
* @private
*/
assignCallbackToDispatcher: {
value: function(eventName, callbackName, dispatcher) {
if (this[callbackName]) {
dispatcher.on(eventName, this[callbackName], this);
} else if (this.options[callbackName]) {
dispatcher.on(eventName, this.options[callbackName], this);
} else {
console.error('Error: No method \'' + callbackName + '\' found on mediator');
}
}
}
});
Mediator.extend = extend;
// =======================================================================
// === Controller ========================================================
// =======================================================================
/**
* Simple controller object.
* @class Controller
* @constructor
* @extends Backbone.Events
* @uses extend
* @TODO Determine what other functionality needs to be a part of the controller.
*/
var Controller = Rebar.Controller = function(options) {
if (!_.isUndefined(options)) {
this.options = options;
_.extend(this, _.pick(this.options, ['model']));
}
};
Controller.prototype = Object.create(Backbone.Events, {
/**
* Reference to the model the controller will be interacting with
* @property model
* @type Backbone.Model
*/
model: {
value: undefined,
writable: true
}
});
Controller.extend = extend;
// =======================================================================
// === Dependency Router =================================================
// =======================================================================
/**
* Handles all pre and post routing functionality. This is the default router when you initialize
* an `Application` instance. Once initialized any time the browser's anchor location changes this
* class notifies the rest of the application of the new directory, file, view and anchor to use.
* To use simply listen to the application's `routeDidChange` or the router's `routeDidChange` event firing
* and then implement the AMD loader that makes the most sense (for your project) to use.
* @class DependencyRouter
* @extends Backbone.Router
* @constructor
* @example
* // requirejs example
* router.on("routeDidChange", function(route){
* var mReq = require([resource], function(a) {
* var Constructor = a[view];
* var v = new Constructor({
* routeData: data
* });
* delegate.addSubView(v);
* }, function(e) {
* console.log("Error: " + e);
* });
* });
*/
var DependencyRouter = Rebar.DependencyRouter = function(options) {
if (!_.isUndefined(options)) {
if (!_.isUndefined(options.landing)) {
this.landing = options.landing;
}
if (!_.isUndefined(options.staticRoutes)) {
for (var route in options.staticRoutes) {
this.setStaticRoute(route, options.staticRoutes[route]);
}
}
}
Backbone.Router.call(this, options);
};
DependencyRouter.prototype = Object.create(Backbone.Router.prototype, {
/**
* Default landing for no hash. Where the browser will be routed to when landing
* on the root url of the application.
* @property landing
* @type {String}
* @default ""
*/
landing: {
value: '',
writable: true
},
/**
* Define only the route hash here because we'll be using dependency routing
* for the rest of the functionality.
* @property routes
* @type {Object} route key value pairs
* @default { "": "handleNoHash", "*splat": "handleAll" }
* @private
*/
routes: {
value: {
'': 'handleNoHash',
'*splat': 'handleAll'
},
writable: true
},
/**
* This object is empty by default, but routes added here, either manually,
* or through the two methods, setStaticRoute and setStaticRoutes, will bypass
* the handleAll and handleNoHash methods referenced in the routes object.
* @property staticRoutes
* @type {Object} static route key value pairs
* @private
*/
staticRoutes: {
value: {},
writable: true
},
/**
* Reroute the page to the page referenced as landing
* @method handleNoHash
* @private
*/
handleNoHash: {
value: function() {
this.handleAll(this.landing + Backbone.history.location.search);
},
writable: true
},
/**
* Handles every route that doesn't match any of the previous matches
* @method handleAll
* @private
*/
handleAll: {
value: function(route) {
// reference the current url from backbone
var routeString = _.isUndefined(route) ? Backbone.history.getFragment() : route;
// check to make sure we dont have any static routes that were added
for (var sRoute in this.staticRoutes) {
if (sRoute === routeString) {
this.staticRoutes[sRoute]();
return;