Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone Router not working with pushState

I want to have every page request redirect to my index.html, and any link (not #urls - /real/urls) clicked in my app to run through router.js so there are essentially no page refreshes - purely ajax. Is there an easy way to do this with Backbone routing and htaccess?

I have it working at the moment if I take away {pushState: true} and format my links like #login. However, when I enable pushState and click on #login, nothing happens. Instead, it is only once I refresh the page that Backbone interprets the #login and follows the route to render loginView.

Here is my router:

// Filename: router.js
define( [ 'views/beta/requestInvite', 'views/beta/login' ],
function(requestInviteView, loginView) {
    var AppRouter = Backbone.Router.extend( {
        routes : {
            // Pages
            'login' : 'login',

            // Default
            '*actions' : 'defaultAction'
        },

        // Pages
        login : function() {
            loginView.render();
        },

        defaultAction : function(actions) {
            requestInviteView.render();
        }
    });

    var initialize = function() {
        var app_router = new AppRouter;
        Backbone.history.start({pushState: true});
    };
    return {
        initialize : initialize
    };
});

What I would like to happen is in requestInviteView, when the link to /login is clicked, the url changes to /login and the loginView is rendered.

Thanks for any help!

like image 742
Garrett Avatar asked Jun 06 '12 06:06

Garrett


1 Answers

Changing from hash to pushstate is not that trivial as changing single parameter as one may be led to think. What i do is catch the click event in my view and call app.navigate to trigger the route.

app.navigate("/login", {trigger: true});

http://backbonejs.org/#Router-navigate

like image 191
Anthony Chua Avatar answered Oct 17 '22 14:10

Anthony Chua