How do I disable backbone history but still allow

2019-03-19 20:50发布

问题:

Say I do the following:

  • Click a link on the homepage (/) and go to /posts/1
  • Trigger an event and go to the backbone route /posts/1/#/1/edit
  • I click back

I need to make it so that the user ends up back on the homepage (/) not back at /posts/1

So I need to allow for backbone hash routes to work but not modify the history. I'd personally prefer to keep the history, but it's a requirement of a project.

回答1:

The latest version of Backbone (0.9.x) has the ability to trigger a route, but not add it to the history.

See Backbone.Router#navigate for the replace:true option.

Basically, just call .navigate on your router with trigger:true (to fire the route) and replace:true (to prevent it going to history)

app.navigate('posts/1/edit',{trigger:true, replace: true});

Here's a jsfiddle showing it in action: http://jsfiddle.net/7Z6ju/1/

  • Click "Post 1" to go to the Post 1 page.
  • Then, click "Edit" to go to the edit page.
  • Then, hit the back button - you should end up back on home.