Patchesoft
Patchesoft

Reputation: 317

How to reload a route using hasher.js and crossroads.js?

I currently have this code:

crossroads.addRoute('/login', function(){
    $.ajax({
        url: '/login',
        type: 'GET',
        data: {

        },
        success: function(msg) {
            $('#' + main_window).html(msg);
        }
    })
});

Along with this hasher.js for maintaining history:

function parseHash(newHash, oldHash){
    crossroads.parse(newHash);
}
hasher.initialized.add(parseHash); //parse initial hash
hasher.changed.add(parseHash); //parse hash changes
hasher.init(); //start listening for history change

$('a').on('click', function(e) {
    e.preventDefault();
    hasher.setHash($(this).attr('href'));
});

Now when I have a link that says #/login and click it, the login page is loaded fine. However, if the user clicks the login link again, the page doesn't reload. I know the click is registering, but the routing/hashing isn't firing. How do I manage to do this?

Any help would be greatly appreciated. Thanks!

Upvotes: 1

Views: 1929

Answers (2)

Chris
Chris

Reputation: 1

Your can force the call of your route by this:

// add this dummy route first
crossroads.addRoute('noop', function() { } );

$('a').on('click', function(e) {
// route to dummy route
hasher.setHash('noop');
// and then replace by your login route
hasher.replaceHash('login');
}

Upvotes: 0

Hugo Silva
Hugo Silva

Reputation: 6958

You are not changing anything with hasher.setHash("#/currentpage") because you are already on that page. So the change event never gets fired. You could probably just go:

$('a').on('click', function(e) {
    e.preventDefault();
    hasher.setHash('');
    hasher.setHash($(this).attr('href'));
});

But that would clutter the history, so you could force a reload on the click, if you make the loading method available:

var loadLogin = function(){
    $.ajax({
        .... your ajax settings ....
    });
};
crossroads.addRoute('/login', loadLogin);

$('a').on('click', function(e) {
    e.preventDefault();
    var newHash = $(this).attr('href');
    if(newHash === '/login' && hasher.getHash() === '/login') {
        loadLogin()
    } else {
        hasher.setHash(newHash);
    }
});

EDIT As @Patchesoft pointed out, crossroads has a property called ignoreState, which will force any request to go though the router function, even if on the current page - https://millermedeiros.github.io/crossroads.js/#crossroads-ignoreState

Upvotes: 3

Related Questions