Silently change the URL to a previous version using Backbone.js

Using Backbone.js, is it possible to transfer the router to the page where it came from? I would like to use this for the case when I change my URL when a popup appears and I want it to change it back when I hide a popup. I don’t want to just come back because I want the background page to be in the same position as me before I show the popup

+8
javascript url pushstate
source share
4 answers

You can solve this problem by extending Backbone.Router and saving all 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 need to reject your modal method, just call the MyRouter.previous() method, which will redirect you back to the last "hash".

+14
source share

I think mateusmaso's answer is mostly right, but it needs some tweaking to ensure that you always get the right url you are looking for.

First you need to override the route method to run the beforeRoute method:

 route: (route, name, callback) => Backbone.Router.prototype.route.call(this, route, name, => @trigger('beforeRoute') callback.apply(this, arguments) ) 

Then you bind the event and initialize the history instance variable:

 initialize: (options) -> @history = [] @on "beforeRoute", @storeRoute 

Next, create helper methods for storing and retrieving the fragment:

 storeRoute: => @history.push Backbone.history.fragment previousFragment: => @history[@history.length-2] 

Finally, you need one last helper method that you can use to change the URL without reloading and saving the resulting snippet. You must use this when closing the popup or you won’t have the expected fragment in your history if the user pops up again without moving to another location. This is because a navigation call without "trigger: true" will not call an event handler to store the fragment.

 changeAndStoreFragment: (fragment) => @navigate(fragment) @storeRoute() 
+1
source share

This answer may not solve this question, but it poses the same problem. I couldn’t calmly navigate the previous route or adjust the route because of the trailing slash. To ensure that route functions do NOT start, use {trigger:false} or do not use a trigger at all, since false is the default behavior and make sure your route starts with #something instead of “# / something” (note the slash ) or modify regEx inside Backbone.js, part of the router.

0
source share

You can call the route in onCloseEvent of your popup or overlay with:

 router.navigate('/lasturl/'); 

This will set the URL. If you pass true as the second parameter, you will also perform the routes action. Otherwise, the page will remain unchanged.

http://documentcloud.github.com/backbone/#Router-navigate

-2
source share

All Articles