Cycs
Cycs

Reputation: 239

Backbone router

I am trying to update the URL but not navigate the page when using tabs in backbone, so that a tab can be bookmarked, when I run this from my codebase it does nothing,

app.Router.navigate('groups/teams', { trigger:false });

however if I run it in my console, it changes the url from 'http://app.local/groups' to 'http://app.local/groups#groups/teams' why does it add #? I would like to update the URL to 'http://app.local/groups/teams'.

Am I using the Router incorrectly? My router is pretty simple,

        var app = app || {};

        var Router = Backbone.Router.extend({

        routes: {

            'groups' : 'groups'

        },

        groups: function() {
             alert("Groups");
        }

    });

    app.Router = new Router();

Upvotes: 3

Views: 215

Answers (3)

V.S.V
V.S.V

Reputation: 302

Add this code to your router initialize: function

 $('body').delegate('a[href]:not([href^=\#])', 'click', function (e) {
       e.preventDefault();
   Backbone.history.navigate($(this).attr('href'), {trigger: true});

});

it work in my case

Upvotes: 0

Simon
Simon

Reputation: 226

hash fragments (#page) were used to provide these permalinks, but with the arrival of the History API,

just set pushState ture:

Backbone.history.start({pushState: true, root: "/public/search/"})

Upvotes: 0

machineghost
machineghost

Reputation: 35723

Normally when you have a URL like:

www.example.com/foo

the foo part is considered to indicate a resource called "foo" on the example.com server. So, if the client (ie. Javascript code) were to redirect the user to "www.example.com/bar", it wouldn't be able to do anything after that, because the browser will take the user to a new page entirely (with entirely new Javascript code).

Most, but not all, modern browsers have implemented a feature called pushstate which gets around this and allows the client to set the URL to "www.example.com/bar" without actually making the browser go back to the server and ask for that page. However, since not all browsers support pushstate, Backbone doesn't use it by default.

Instead Backbone takes advantage of an old piece of web technology: the anchor/hash (ie. www.example.com/#foo). If you don't want it to do that you have to pass pushState: true, hashChange: false options when you start your router. However, even if you do that Backbone will still fall back to hash-based navigation if the browser doesn't support pushstate, so there's no guarantee that it won't still do the "#bar" thing.

My advice would be to adjust to having all of your client-side routes be hash-based, but if you are certain that all of your users will use push-state-enabled browsers, you could use that approach. The browsers which support push state can be found here:

http://caniuse.com/#search=pushstate

Hope that helps.

Upvotes: 0

Related Questions