Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // encoding: windows-1251
- (function() {
- function Router() {
- var t = this, routes = [];
- t.addRoute = function(rule, cb) {
- if ( ( typeof rule == 'string' || (typeof rule == 'object' && rule.constructor == RegExp) ) && typeof cb == 'function') {
- routes.push(rule, cb);
- }
- };
- t.run = function() {
- var cur, fn;
- (fn = function() {
- if (cur != location.href) {
- cur = location.href;
- // вызывается каждый раз при изменении местоположения
- if (typeof t.onLocationChange == 'function') {
- t.onLocationChange();
- }
- // обрабатываем маршруты
- for (var i = 0, l = routes.length, match; i < l; ++i) {
- if (typeof routes[i] == 'string') {
- if (routes[i] == location.pathname) {
- return routes[++i]();
- }
- }
- else {
- match = routes[i].exec(location.pathname);
- if (match) {
- return routes[++i].apply( null, match.slice(1) );
- }
- }
- ++i;
- }
- // если маршрут не найден
- if (typeof t.defaultRoute == 'function') {
- t.defaultRoute();
- }
- }
- })();
- setInterval(fn, 40);
- };
- }
- var router = new Router;
- router.onLocationChange = function() {
- alert('Адрес изменился');
- };
- router.defaultRoute = function() {
- alert('Действие по-умолчанию');
- };
- router.addRoute('/friends', function() {
- alert('Делаем что-то с друзьями');
- });
- router.run();
- })();
Advertisement
Add Comment
Please, Sign In to add comment