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

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

问题描述

我写Backbone.js的使用一个应用程序,并正在页面之间动画(有点像iPhone风格的UI)。所以,当你点击一个按钮,下一个页面从右侧滑入,然后单击后退按钮会使下页幻灯片从左边。我希望能够做同样的与浏览器的前进和后退按钮,使用路由器。是否有可能知道这​​是pressed,(向前或向后),这样我可以确保动画是在正确的方向吗?

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?

感谢

推荐答案

监听所有链接点击事件。 (CoffeeScript的)

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

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

另外,你可以拦截 Backbone.history.navigate()的如果有人点击它,这意味着他们不会回来,所以设置一个标志,真正。也有一个事件在你的路由器听取所有路由器事件。始终保存previous片段( Backbone.history.getFragment())。比较与previous片段的当前片段。如果它们是相同的,然后检查该标志设置为真正。如果设置为,那么你知道它是回来,如果真正那么它是不是和别人点击一个链接,但得出了相同的previous页面。最后,该标志复位为

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

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

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