骨干路由检测是向前还是向后按下 [英] backbone routing detecting whether forward or back pressed

查看:21
本文介绍了骨干路由检测是向前还是向后按下的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用backbone.js 编写一个应用程序,并在页面之间制作动画(有点像iphone 风格的用户界面).所以当你点击一个按钮时,下一页从右侧滑入,而点击后退按钮将使下一页从左侧滑入.我希望能够使用路由器对浏览器的前进和后退按钮执行相同的操作.是否可以分辨按下的是哪个(向前或向后),以便我可以确保动画在正确的方向上?

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?

澄清一下,我不是在问如何进行骨干路由.我在问在进行主干路由时,如何捕捉导致 url 更改的按钮,是后退按钮还是前进按钮?

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?

谢谢

推荐答案

监听所有链接上的点击事件.(咖啡脚本)

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

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

或者,你可以拦截Backbone.history.navigate().如果有人点击它,那就意味着他们不会回去,所以设置一个标志为真实.在您的路由器中也有一个事件监听所有路由器事件.始终存储前一个片段 (Backbone.history.getFragment()).将当前片段与前一个片段进行比较.如果它们相同,则检查该标志是否设置为 truefalse.如果设置为 false,那么你知道它回来了,如果 true 那么它不是,有人点击了一个链接,但来到了同一个前一页.最后,将此标志重置为 false.

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()

现在很简单

# 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).

这篇关于骨干路由检测是向前还是向后按下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆