-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlazy-router.js
94 lines (82 loc) · 3.09 KB
/
lazy-router.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
define(function () {
var Router = function (options) {
options || (options = {});
if (options.routes) this.routes = options.routes;
this._bindRoutes();
this.initialize.apply(this, arguments);
};
_.extend(Router.prototype, Backbone.Events, {
initialize: function () {
},
routes: {},
router: null,
navigate: function (fragment, options) {
Backbone.history.navigate(fragment, options);
return this;
},
_bindRoutes: function () {
var router = this;
var routes = {};
_.forEach(this.routes, function (controller, route) {
routes[route] = this._processController(controller);
}, this);
this.router = new Backbone.Router({
routes: routes
});
},
_processController: function (controller) {
var result = null;
var self = this;
if (typeof controller == 'function') {
result = function () {
self.trigger('preAction');
controller.apply(controller, arguments);
self.trigger('postAction');
};
} else {
if (typeof self[controller] == 'function') {
result = function () {
self.trigger('preAction');
self[controller].apply(controller, arguments);
self.trigger('postAction');
};
} else {
var action = 'index';
if (controller.match('@')) {
var arr = controller.split('@');
controller = arr[0];
action = arr[1];
}
result = function () {
var args = arguments;
require([
controller
], function (controller) {
self.trigger('preAction');
if (typeof controller == 'function') {
controller.apply(controller, args);
} else {
controller[action].apply(controller, args);
}
self.trigger('postAction');
});
}
}
}
return result;
},
route: function (route, name, callback) {
if (!_.isRegExp(route)) route = this._routeToRegExp(route);
if (typeof callback == 'undefined') {
callback = name;
this.router.route(route, this._processController(callback));
} else {
this.router.route(route, name, this._processController(callback));
}
return this;
},
_routeToRegExp: Backbone.Router.prototype._routeToRegExp
});
Router.extend = Backbone.History.extend;
return Router;
});