34

Is there a general event that fires every time we navigate to a different URL?

window.App =
  Models: {}
  Collections: {}
  Views: {}
  Routers: {}

  init: ->
    # Initialize Routers
    new App.Routers.Main()

    # Initialize History
    Backbone.history.start(pushState: true)

    # BIND VIEW CHANGE?
    $(@).on 'changeOfRoute', -> 
      console.log "Different Page" 

$(document).ready ->
  App.init()

Doing this per view is possible, but I'm looking for a general solution.

Rob Hruska
  • 118,520
  • 32
  • 167
  • 192
TTT
  • 6,505
  • 10
  • 56
  • 82

4 Answers4

49

There is the "route" event on the Router:

http://backbonejs.org/#Events-catalog

  • "route" (router, route, params) — Fired by history (or router) when any route has been matched.

This allows you to bind to specific routes.

If you want to fire a handler after any route, bind to "route", and the route will be the first argument:

myRouter.on("route", function(route, params) {
    console.log("Different Page: " + route);
});

This will only trigger events for your explicitly defined routes. If you want to trigger events for routes that are not explicitly defined, then add a 'splat' route as per How to detect invalid route and trigger function in Backbone.Controller

Community
  • 1
  • 1
Edward M Smith
  • 10,627
  • 2
  • 46
  • 50
  • 2
    Thanks, this works. However, the event fires after the route has changed. Is there an event that fires if a route change is started? – TTT Mar 06 '12 at 09:22
  • 2
    Looks like the 1.1.x release has Router.execute, which fires _before_ each route. http://backbonejs.org/#Router-execute – zedd45 Apr 15 '14 at 20:38
  • fyi, the route and history `route` events are now split out – Ben Creasy Dec 05 '16 at 17:30
2

From the Backbone docs

This method is called internally within the router, whenever a route matches and its corresponding callback is about to be executed. Override it to perform custom parsing or wrapping of your routes, for example, to parse query strings before handing them to your route callback, like so:

var Router = Backbone.Router.extend({
  execute: function(callback, args) {
    args.push(parseQueryString(args.pop()));
    if (callback) callback.apply(this, args);
  }
});

This site has some useful code for redefining the Router to support 'before' and 'after' hooks, though it would require updating with each version-change of Backbone.

Paul
  • 19,704
  • 14
  • 78
  • 96
Lee Goddard
  • 10,680
  • 4
  • 46
  • 63
0

@TTT: Unfortunately Backbone doesn't give us a before/after event, so you will need to overwrite or extend the Router.route. You can find the way to do that in this answer: https://stackoverflow.com/a/16298966/2330244

Community
  • 1
  • 1
Jesús Carrera
  • 11,275
  • 4
  • 63
  • 55
0

May be this extension would be useful for you: https://github.com/zelibobla/Backbone.RewindableRoute/blob/master/backbone.rewindableRoute.js

zelibobla
  • 1,498
  • 1
  • 16
  • 23