Backbone.js change url without reloading the page

百般思念 提交于 2019-12-05 04:25:53
Peter Berg

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.

Routers are your friend in this situation. Basically, create a router that has several different routes. Your routes will call different views. These views will just affect the portions of the page that you define. I'm not sure if this video will help, but it may give you some idea of how routers interact with the page: http://www.youtube.com/watch?v=T4iPnh-qago

Here's a rudimentary example:

myapp.Router = Backbone.Router.extend({

    routes: {
        'link1': 'dosomething1',
        'link2': 'dosomething2',
        'link3': 'dosomething3'
    },

    dosomething1: function() {
        new myapp.MyView();
    },
    dosomething2: function() {
        new myapp.MyView2();
    },
    dosomething3: function() {
        new myapp.MyView3();
    }

});

Then your url will look like this: www.mydomain.com/#link1.

Also, because <a href=''></a> tags will automatically call a page refresh, make sure you are calling .preventDefault(); on them if you don't want the page to refresh.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!