Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbone routing detecting whether forward or back pressed

Tags:

backbone.js

I am writing an app using backbone.js, and am animating between pages (a bit like the iphone style ui). So when you click on a button, the next page slides in from the right, and clicking a back button will make the next page slide in from the left. I want to be able to do the same with the browser forward and back buttons, using a Router. Is it possible to tell which was pressed, (forward or back) so that I can ensure that the animation is in the correct direction?

Just to clarify, I'm not asking how to do backbone routing. I'm asking when doing backbone routing, how you can catch which button caused the url to change, was it the back button or forward button?

Thanks

like image 377
dan Avatar asked Apr 23 '12 16:04

dan


1 Answers

Listen for a click event on all links. (CoffeeScript)

$(document).on 'click', 'a' ->
  window.linkClicked = true

Alternatively, you can intercept Backbone.history.navigate(). If someone clicks it, that means they are not going back, so set a flag to true. Also have an event in your router listening to all router events. Always store the previous fragment (Backbone.history.getFragment()). Compare the current fragment with the previous fragment. If they are the same, then check if that flag was set to true or false. If set to false, then you know it was back, if true then it's not and that someone clicked a link but came to the same previous page. Finally, reset this flag to false.

class SnazzyRouter extends Backbone.Router
    initialize: ->
      # This gets triggered everytime a route event gets triggered
      @on 'all', =>
          currentFragment = Backbone.history.getFragment()
          window.backDetected = false  # assume no back detected

          if !window.linkClicked and currentFragment == window.previousFragment
              window.backDetected = true

          window.linkClicked = false  # reset
          window.previousFragment = currentFragment

window.linkClicked = false
window.backDetected = false
window.previousFragment = null

snazzyRouter = new SnazzyRouter()

Now, it's a simple

# Did we go back?
console.log "I CAN'T BELIEVE WE WENT BACK!" if window.backDetected

Let me know if you need any clarifications (I just implemented this for my app and it works).

like image 92
axsuul Avatar answered Nov 02 '22 20:11

axsuul