Silver Ringvee Silver Ringvee - 25 days ago 12
Javascript Question

Get route on page load

How to get current route on (first) page load?

myRouter = new app.Router();
Backbone.history.start();

myRouter.on("route", function(route, params) {
console.log(route);
});


This works on every route but not the first one (or page refresh).

Answer

The reason it doesn't work is that you are binding an event after the event was triggered.

This would solve the problem:

myRouter = new app.Router();
myRouter.once("route", function(route, params) {
    console.log(route);
});
Backbone.history.start();

But a better way would be that in your router, you use listenToOne.

app.Router = Backbone.Router.extend({
    routes: { /* ... */ },
    initialize: function() {

        this.listenToOnce(this, 'route', this.onFirstRoute);
    },
    onFirstRoute: function(route, params) {
        console.log(route);
    }
});

It will trigger once, then it'll unbind itself.

Or, if you only want to know which route:

myRouter = new app.Router();
Backbone.history.start();

console.log(Backbone.history.getFragment()); // or .getPath()
Comments