Silently change url to previous using Backbone.js

user802232 picture user802232 · Dec 7, 2011 · Viewed 11.4k times · Source

Using Backbone.js, is it possible to make the router navigate to the page where it came from? I'd like to use that for the case where I change my URL when a popup appears, and I want go change it back, when I hide the popup. I don't want to simply go back, because I want to keep the background page in precisely the same position as I left it before I showed the popup

Answer

mateusmaso picture mateusmaso · Apr 28, 2012

You can solve this problem by extending Backbone.Router and storing all the routes during navigation.

class MyRouter extends Backbone.Router
  constructor: (options) ->
    @on "all", @storeRoute
    @history = []
    super options

  storeRoute: ->
    @history.push Backbone.history.fragment

  previous: ->
    if @history.length > 1
      @navigate @history[@history.length-2], true 

Then, when you have to dismiss your modal, simply call the MyRouter.previous() method that it will redirect you back to the last "hash".