Search code examples
javascriptbackbone.jsbackbone-routing

What's the difference between Backbone.history.navigate and this.router.navigate


What is the difference between Backbone.history.navigate and this.router.navigate?

Why would sometimes the former work while later won't?


Solution

  • If you look at the Backbone source, you'll see that Router.prototype.navigate is simply a proxy to Backbone.history.navigate which you can call anywhere without the need for a router instance.

    // Simple proxy to `Backbone.history` to save a fragment into the history.
    navigate: function(fragment, options) {
      Backbone.history.navigate(fragment, options);
      return this;
    },
    

    Routing is handled in a global, namespaced in Backbone, History instance.

    This is meant to let developer create their own History class and then to overwrite the Backbone.history property to globally change the routing behaviour.

    The History class isn't documented much, but it's well commented in the source.

    Also, having a proxy to navigate in the Router class makes it easy to hook our own behaviour in the router directly.


    As to why sometimes it doesn't work is probably because you're trying to do this.router.navigate in a class where this.router doesn't exist.