Backbone.js change url without reloading the page

Peter Berg picture Peter Berg · Jul 9, 2013 · Viewed 11.7k times · Source

I have a site that has a user page. On that page, there are several links that let you explore the user's profile. I'd like to make it so that, when one of those links is clicked on, the url changes, but the top third of the page containing the user's banner doesn't reload.

I'm using Backbone.js

I have a feeling that I'm in one of those situation where I have such a poor understanding of the problem I'm dealing with that I'm asking the wrong question, so please let me know if that appears to be the case

Answer

Peter Berg picture Peter Berg · Jul 10, 2013

My mistake was assuming that there was a special, built-in way of doing this in backbone. There isn't.

Simply running the following line of code

window.history.pushState('object or string', 'Title', '/new-url');

will cause your browser's URL to change without reloading the page. You can open up the javascript console in your browser right now and try it with this page. This article explains how it works in more detail (as noted in this SO post).

Now I've just bound the following event to the document object (I'm running a single page site):

bindEvents: () ->
    $(document).on('click', 'a', @pushstateClick)


pushstateClick: (e) ->
    href = e.target.href || $(e.target).parents('a')[0].href
    if MyApp.isOutsideLink(href) == false
        if e.metaKey 
                      #don't do anything if the user is holding down ctrl or cmd; 
                      #let the link open up in a new tab
        else
            e.preventDefault()
            window.history.pushState('', '', href);
            Backbone.history.checkUrl()

See this post for more info.

Note that you CAN pass the option pushstate: true to your call to Backbone.history.start(), but this merely makes it so that navigating directly to a certain page (e.g. example.com/exampleuser/followers) will trigger a backbone route rather than simply leading to nowhere.