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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With