如何在 Backbone.js 中跟踪路由器更改事件
每次应用程序在 Backbone.js 中切换 URL 时,我都需要运行一个函数,并且我需要知道 URL 已更改为的主题标签。我假设有一个可以绑定的事件,但我无法弄清楚要绑定到哪个事件和哪个对象。
具体来说,我想将新 URL 发送到分析应用程序。
I need to run a function every time the application switches URLs in Backbone.js, and I need to know the hashtag the URL has changed to. I'm assuming there is an event that I can bind to but I haven't been able to figure out which event and what object to bind to.
Specifically I want to ship the new URL to an analytics application.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我知道这是一篇旧文章,但就像 @kirk 所建议的那样,Backbone.js 已经构建了它。
我认为你最好使用这种方法。
I know this is an old post, but like @kirk suggested, Backbone.js already has it built it.
I think you'd be better off using this method.
@qwertymk 已经完成一半了。您可以在 window 对象上查找 hashchange 事件:
@qwertymk was half way there. You can look for the hashchange event on the window object:
将其放在代码的顶部,
上面的代码将包装 History.navigate 函数,并在调用时触发“before:url-change”和“url-changed”
稍后您可以使用
put this somewhere top in your code
the code above will wrap History.navigate function and will trigger "before:url-change" and "url-changed" when it is called
Later you can use
还有另一个“Backbone.history.on('route', ...)”事件,也可以工作,您可以发现它在库中被触发):
它更精确,因为“all”是包罗万象的:
引用 Backbone 文档:
顺便说一句,Backbone 最佳实践是使用 ListenTo 方法,例如:
这样您就不需要手动清理事件侦听器 - 相反,它在逻辑上绑定到视图/模型/等。使用它的。
There is another, "Backbone.history.on('route', ...)" event, that works too and you can find it being triggered in the library):
It is more precise, because 'all' is a catch all:
Quote from Backbone documentation:
By the way, Backbone best practice is to use listenTo method, e.g.:
This way you don't need to clean up the event listener manually - instead it is logically bound to the view/model/etc. that uses it.