/
marionette.approuter.js
66 lines (56 loc) · 1.86 KB
/
marionette.approuter.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
// AppRouter
// ---------
// Reduce the boilerplate code of handling route events
// and then calling a single method on another object.
// Have your routers configured to call the method on
// your object, directly.
//
// Configure an AppRouter with `appRoutes`.
//
// App routers can only take one `controller` object.
// It is recommended that you divide your controller
// objects in to smaller peices of related functionality
// and have multiple routers / controllers, instead of
// just one giant router and controller.
//
// You can also add standard routes to an AppRouter.
Marionette.AppRouter = Backbone.Router.extend({
constructor: function(options){
Backbone.Router.prototype.constructor.call(this, options);
if (this.appRoutes){
var controller = this.controller;
if (options && options.controller) {
controller = options.controller;
}
this.processAppRoutes(controller, this.appRoutes);
}
},
// Internal method to process the `appRoutes` for the
// router, and turn them in to routes that trigger the
// specified method on the specified `controller`.
processAppRoutes: function(controller, appRoutes){
var method, methodName;
var route, routesLength, i;
var routes = [];
var router = this;
for(route in appRoutes){
if (appRoutes.hasOwnProperty(route)){
routes.unshift([route, appRoutes[route]]);
}
}
routesLength = routes.length;
for (i = 0; i < routesLength; i++){
route = routes[i][0];
methodName = routes[i][1];
method = controller[methodName];
if (!method){
var msg = "Method '" + methodName + "' was not found on the controller";
var err = new Error(msg);
err.name = "NoMethodError";
throw err;
}
method = _.bind(method, controller);
router.route(route, methodName, method);
}
}
});