Skip to content

Instantly share code, notes, and snippets.

@davepermen
Last active December 16, 2015 08:08
Show Gist options
  • Save davepermen/5403453 to your computer and use it in GitHub Desktop.
Save davepermen/5403453 to your computer and use it in GitHub Desktop.
Simple jquery less mini "sammyjs"
Path.setup(function () {
this.get('/yadda', function () {
document.querySelector('h1').innerHTML = "OMG";
});
this.get('/yaddaweeehhh', function () {
document.querySelector('h1').innerHTML = "<a href='/yaddaNEW'>NEW LINK!!!!</a>";
});
this.get('/yaddaNEW', function () {
document.querySelector('h1').innerHTML = "OMG!!";
});
this.get('/blog/##/##/##', function (year, month, day) {
document.querySelector('#content').innerHTML = "blog entry from " + year + "-" + month + "-" + day;
});
this.get('/blog/##', function (year, month, day) {
document.querySelector('#content').innerHTML = "blog entry from " + year + "-" + month + "-" + day;
});
this.all(function () {
document.querySelector('p').innerHTML = this.path;
console.log(this.path);
});
});
var Path = function () {
var refreshLinks = function () {
[].forEach.call(document.querySelectorAll('a[href^="/"]'), function (link) {
if (link.getAttribute('data-Path-click-handler') !== 'bound') {
link.setAttribute('data-Path-click-handler', 'bound');
link.addEventListener('click', function (event) {
Path.go(link.getAttribute('href'));
event.preventDefault();
});
}
});
};
var handleDefault = function (path) {
Path.process(path, handleDefault.handler);
refreshLinks();
};
return {
go: function (path) {
if (history.pushState !== undefined) {
history.isActive = true;
history.pushState(null, null, path);
handleDefault(path);
} else {
location.pathname = path;
}
},
process: function (path, handler) {
handler.call({
get: function (route, handler) {
if (route.exec !== undefined) {
// regex way
var params = route.exec(path);
if (params !== null) {
handler.apply({ path: path }, params.slice(1));
}
} else if (route.indexOf('##') >= 0) {
// doublehash (replaces doubledash with finding tokens till the ending '/'s, and make sure it's the full path)
var params = new RegExp('^' + route.replace(/##/g, '([^/]+)') + '$').exec(path);
if (params !== null) {
handler.apply({ path: path }, params.slice(1));
}
} else if (route === path || (route === '/' && path === '')) {
// static route
handler.call({ path: path });
}
},
all: function (handler) {
handler.call({ path: path });
}
});
},
setup: function (handler) {
handleDefault.handler = handler;
window.addEventListener('load', function () { handleDefault(location.pathname); });
if (history.pushState !== undefined) {
window.addEventListener('popstate', function () { history.isActive && handleDefault(location.pathname); });
refreshLinks();
}
}
};
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment