Skip to content

Instantly share code, notes, and snippets.

@feroult
Created August 7, 2014 11:06
Show Gist options
  • Save feroult/501d6b21bbcc0362a264 to your computer and use it in GitHub Desktop.
Save feroult/501d6b21bbcc0362a264 to your computer and use it in GitHub Desktop.
goog.provide('n');
module(n, function() {
var started = false;
function go(path, callback) {
var controllerInfo = parse(path);
window[controllerInfo.controller][controllerInfo.action].call(this, controllerInfo.params, callback);
window.history.pushState('wink', "", path);
$('.dropdown.open .dropdown-toggle').dropdown('toggle');
}
function back(path) {
var controllerInfo = parse(path);
window[controllerInfo.controller][controllerInfo.action].call(this, controllerInfo.params);
}
function success(path, message) {
go(path, function() {
var divText = v.layouts.alert({
type : 'success',
message : '<strong>Muito bem!</strong> ' + message
});
$('.messages').append(divText).hide().fadeIn(1000);
});
}
function init() {
bindLinkHandler();
started = true;
// console.log('wink navigation started');
}
function bindLinkHandler() {
if ($('a').length == 0) {
// take care, pages without links will need another solution
return;
}
$('a').live('click', function(e) {
// Fallback for browser that don't support the history API
if (!('replaceState' in window.history)) {
return true;
}
// Ensure middle, control and command clicks act normally
if (e.which == 2 || e.metaKey || e.ctrlKey) {
return true;
}
e.preventDefault();
if (e.target.getAttribute('href') != '#') {
go(e.target.pathname);
}
return false;
});
}
function listenEvents() {
window.onpopstate = function(event) {
if (event.state || started) {
if (started) {
// throw error('invalid state: ' + event.state);
return false;
}
back(location.pathname);
} else {
// first page load
if (!started) {
init();
return;
}
}
}
}
listenEvents();
function controllerName(s) {
var words = s.split(/\s|_/);
for (var i = 0, l = words.length; i < l; i++) {
if (i == 0) {
continue;
}
words[i] = words[i].substr(0, 1).toUpperCase() + (words[i].length > 1 ? words[i].substr(1) : '');
}
return words.join('');
}
function parse(path) {
var parts = path.split('/');
if (parts.length == 2) {
return {
controller : controllerName(parts[1]),
action : 'indexAction',
params : {}
}
}
if (parts.length == 3) {
return {
controller : controllerName(parts[1]),
action : parts[2] + 'Action',
params : {}
}
}
return {
controller : controllerName(parts[1]),
action : parts[3] + 'Action',
params : {
id : parts[2]
}
}
}
return {
parse : parse,
go : go,
success : success
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment