-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlennon.js
184 lines (139 loc) · 7.17 KB
/
lennon.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
/*!
* Lennon v0.1
*
* An extremely lightweight router that uses the History API and falls back to hash.
*
* @author Gabe Hayes <[email protected]>
* @copyright 2013, Gabe Hayes
*/
(function(window, $, undefined) {
'use strict';
return window.Lennon = function(opts) {
var current_route,
initialized = false,
options = $.extend({
//-- determines whether or not the history api is enabled
historyEnabled: !!(window.history && window.history.pushState),
//-- a jQuery selector for links that will have routing behavior applied to them
linkSelector: 'a[target!=_blank]:not([href^=http])',
//-- the logger requires error, info and warn methods
logger: window.console,
//-- the publish event that will dispatch the registered event name
publishEvent: null
}, opts),
routes = [],
initialize = function(router) {
var processRoute = function() {
router.process();
};
if ( !initialized ) {
$(document).on('click', options.linkSelector, function() {
var $this = $(this),
href = $this.attr('href');
//-- Use pushstate on anchor clicks
if ( options.historyEnabled ) {
window.history.pushState(null, null, href);
processRoute();
return false;
//-- Hashify internal links if history is not available
} else {
if ( !$this.data('lennonized') ) {
$this.attr('href', '/#' + href).data('lennonized', true);
}
}
});
$(window).on(options.historyEnabled? 'popstate' : 'hashchange', processRoute);
initialized = true;
}
};
return (function() {
return {
define: function(pathName, eventName, exitEventName) {
var occurence = pathName.match(/:/g) || [],
pattern = new RegExp('^' + pathName.replace(/\//g, "\\/").replace(/:(\w*)/g,"(\\w*)") + '$'),
route = {
eventName: eventName,
exitEventName: exitEventName,
paramCount: occurence.length,
path: pathName,
pattern: pattern
};
//-- If the eventName is a string, we require a publishEvent
if ( 'string' === typeof eventName && !options.publishEvent ) {
throw new Error('Cannot publish the event "' + eventName + '" for the route "' + pathName + '". No publishEvent has been provided.');
}
//-- Add the route
options.logger.info('Adding route', pathName, route);
routes.push(route);
//-- Make sure we have initialized
initialize(this);
},
dispatch: function(route, context) {
var e;
options.logger.info('Dispatching', route.path, 'with', context);
//-- Execute the callback
if ( 'function' === typeof route.eventName ) {
e = route.eventName(context || {});
//-- Run the publish event
} else {
e = options.publishEvent(route.eventName, context || {});
}
return e;
},
process: function() {
var context = {},
i, j,
paramKeys,
params,
path = options.historyEnabled? window.location.pathname : window.location.hash.replace('#', '') || '/';
//-- If we land on the page with a hash value and history is enabled, redirect to the non-hash page
if ( window.location.hash && options.historyEnabled ) {
window.location.href = window.location.hash.replace('#', '');
//-- If we land on the page with a path and history is disabled, redirect to the hash page
} else if ( '/' !== window.location.pathname && !options.historyEnabled ) {
window.location.href = '/#' + window.location.pathname;
}
//-- Process the route
options.logger.info('Processing path', path);
for ( i in routes ) {
//-- See if the currently evaluated route matches the current path
params = path.match(routes[i].pattern);
//-- If there is a match, extract the path values and match them to their variable names for context
if ( params ) {
paramKeys = routes[i].path.match(/:(\w*)/g,"(\\w*)");
for ( j = 1; j <= routes[i].paramCount; j++ ) {
context[paramKeys[j - 1].replace(/:/g, '')] = params[j];
}
if ( current_route ) {
//-- Don't dispatch the route we are already on
if ( current_route.path === routes[i].path ) {
return false;
}
//-- Dispatch the exit event for the route we are leaving
if ( current_route.exitEventName ) {
options.logger.info('Exiting', current_route.path, 'with', context || {});
//-- Execute the callback
if ( 'function' === typeof current_route.exitEventName ) {
current_route.exitEventName(context || {});
//-- Run the publish event
} else {
options.publishEvent(current_route.exitEventName, context || {});
}
}
}
//-- Update the current route
current_route = routes[i];
//-- Dispatch
return this.dispatch(routes[i], context);
}
}
//-- No route has been found, hence, nothing dispatched
options.logger.warn('No route dispatched');
}
};
}());
};
}(this, jQuery));
if ( typeof define === "function" && define.amd ) {
define( "Lennon", [], function () { return Lennon; } );
}