Search code examples
backbone.js

Backbone.js: get current route


Using Backbone, is it possible for me to get the name of the current route? I know how to bind to route change events, but I'd like to be able to determine the current route at other times, in between changes.


Solution

  • If you have instantiated a Router in your application, the following line returns the current fragment:

    Backbone.history.getFragment();
    

    From the Backbone.js documentation:

    " [...] History serves as a global router (per frame) to handle hashchange events or pushState, match the appropriate route, and trigger callbacks. You shouldn't ever have to create one of these yourself — you should use the reference to Backbone.history that will be created for you automatically if you make use of Routers with routes. [...]"

    If you need the name of the function bound to that fragment, you can make something like this inside the scope of your Router:

    alert( this.routes[Backbone.history.getFragment()] );
    

    Or like this from outside your router:

    alert( myRouter.routes[Backbone.history.getFragment()] );