Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Backbone.history to go back without triggering route function

Tags:

backbone.js

I have a modal popup which when opened changes the URL. When a user closes the popup I want to go back to the previous URL but I don't want to trigger the route associated with that URL because that will reload my collection and render the view etc. Is there a way to callwindow.history.back()without triggering the route, or is there a backbone equivalent of this?

The only solution I can think of would be to save the previous route, then when the modal is closed call

Backbone.history.navigate(route, {trigger: false, replace: true});

but this seems like a complex way to solve an easy problem.

like image 225
Barny Avatar asked Jul 06 '12 15:07

Barny


1 Answers

Storing history in a router sounds like a good solution to me, I couldn't figure out better way to solve this problem.

A good solution of that is here: Silently change url to previous using Backbone.js

I would do a minor tweak so it would look like this:

class MyRouter extends Backbone.Router

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

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

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

Then you can just call MyRouter.previous(), and if you came by direct request, it will bring you to your root.

I wish it were a default feature of the router, at least so that it keeps 5 last routes.

like image 69
Mïchael Makaröv Avatar answered Oct 15 '22 06:10

Mïchael Makaröv