Search code examples
javascriptbackbone.jsbackbone-viewsbackbone-routing

Backbone.js router pattern for different response to browser "back" button or direct navigation


Is there a good pattern for implementing a Backbone.js Router that responds differently for these two events:

  • Direct navigation - A user navigates directly to page by putting the url directly into the browser or in the application via a call to Router.navigate()
  • Browser "back" button - The user presses the "back" button to go to a page that they were at previously.

The reason I ask is because if the router is called as a result of the user pressing the "back" button, I'd like to just put the old view back into its element via $('element_id').html(view.el) without the reloading data into the model and re-rendering the view.

If the router is called as a result of the user navigating directly to the page by entering the url into the browser, clicking on a link, or a call to Router.navigate() from within the application, I would like the router to instruct the model to re-request data and trigger a re-rendering of the view.

Any help and suggestions would be appreciated, thanks so much!


Solution

  • I faced a similar problem a while back. This may be more than what you want, but here's what I found works.

    Direct navigation

    For direct navigation, the usual flow is something like this:

    • Initialize the app: Most backbone.js projects will have some code that initializes the app (App.init). Although a lot of examples insert the JSON for the collection (todos, etc.) in the actual HTML, I personally like to use this code as an opportunity to fetch the collection after the page has loaded, something like this (coffeescript):

      window.App =
        ...
        init: ->
          @todos = new App.Todos()
          @todos.deferred = @todos.fetch()
      
          @threads.deferred.done ->
            App.appRouter = new App.AppRouter(collection: self.todos)
            ...
      

      (The use of jQuery's deferred is to make sure that the collection is fetched before actually rendering the page.)

    • Initialize the router: Here you get a chance to assign an element to the router and assign the collection to the router (I'm using the 'SwappingRouter' from thoughtbot's backbone-support, which I highly recommend checking out):

      App.Router = Support.SwappingRouter.extend
      ...
        initialize: (options) ->
          @el = $('.content')
          @collection = options.collection
      
    • Execute the route handler: This is the last step, at which point the collection is already initialized and the router has a pointer to it, so we just have to create the view and render it:

        show: (id) ->
          view = new App.TodosView(model: @collection.get(id))
          @swap(view)
      

      (Swap renders the view and does a few other things to clean up.)

    Browser back button

    In this case, neither App.init nor AppRouter.initialize is called, so the collection by default won't be reloaded. Backbone will automatically call navigate on the previous route, so depending on what's in your route handler, the view may be re-rendered. In the example above, it would be (swap calls render), but you could work around this.

    The key problem here and always with backbone is that you're working with a state-less (HTTP) protocol and a state-ful (rich client-side app) environment at the same time. Lining the two up so they work well together can be pretty tricky.