Silver Ringvee
Silver Ringvee

Reputation: 5535

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).

Upvotes: 1

Views: 582

Answers (1)

Emile Bergeron
Emile Bergeron

Reputation: 17430

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 listenToOnce.

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()

Upvotes: 2

Related Questions