Search code examples
javascriptjqueryhandlebars.jscrossroadsjs

Refresh hasherJS/crossroadsJS routes


I’m utilizing crossroadsJS and hasherJS on an SPA powered by handlebarsJS. In retrospect I probably should have built the whole thing on Ember, but this late in it’s not wise to start over.

I have hash routes set up that switch my handlebars templates in and out based on whatever was clicked. I’m able to move backwards and forwards between the routes with no problem. However, if I refresh the page, I’m always brought back to my #/home view. I’ve done some research into window.onhashchange and window.onbeforeunload, but none of these seem to be solving the issue.

I have a very specific way of how I’m handling my views. I have a global views object constructed like so:

views.procedures = function (template) {

    this.initialize = function () {
        this.el = $('<div/>');
        this.el.attr('id', 'procedures');
        this.el.on('click', '.returned-list li a', this.toResults); // list of API objects by name
    };

    this.render = function () {
        var parts = {
            title: 'Procedures View',
        };
        this.el.html(template(parts));
        return this;
    };

    this.toResults = function () {
        cache.justClicked = $(this).attr('data-id');

        crossroads.addRoute('procedures/{name}', function () {
            api.endpoints.procedure(cache.justClicked); // constructed elsewhere
        });
    };

    this.initialize();
};

I mention this because I can’t simply add in JQuery listeners for any type of hash changes in a $(document).ready() or $(window).onhashchange

I’ve read through both the hasherJS and crossroadsJS documentations multiple times, but I’m not able to think of anything to solve the refresh issue. Thanks in advance for any help.


Solution

  • I would need more information from you, but I'm assuming you're doing

    var DEFAULT_HASH = 'home';
    
    if (! hasher.getHash()) {
        hasher.setHash(DEFAULT_HASH);
    }
    

    This is basically saying your default route is always going to be your home route, which is why you're seeing it when you refresh your current route. Try the following:

    var DEFAULT_HASH = 'home', url = hasher.getBaseURL();
    
    if (hasher.getURL() === url) {
        hasher.setHash(DEFAULT_HASH);
    }
    

    This will check to see what your base URL is (the one that's loaded when you first visit the page) and append a #/home route to the base URL, allowing you to refresh your currently viewed route.

    Hope this helps.