【发布时间】:2013-09-12 09:09:47
【问题描述】:
我有一个主干路由器,其中注册了两条这样的路由
routes:{
"":"list",
"restaurants/:id":"restoDetails"
},
在应用程序的根目录,当我列出餐馆时,我为列表中的每个成员创建链接
<script id="restaurantListView" type="text/underscore">
<a href="#restaurants/{{= id }}" class="thumbnail plain">
<h5>{{= name }}</h5>
</a>
</script>
当我点击链接时,它会在 url 栏中创建一个这样的链接
http://localhost:3000/#restaurants/4
但是,没有迹象表明 restoDetails 函数被调用,这与您对路由器中注册的路由的预期相反。例如,这不是记录:
restoDetails:function (id) {
console.log('resto');
}
但是,如果我使用像 http://localhost:3000/#restaurants/4 这样的 url 刷新页面,它会更改为相同的内容,但没有哈希
http://localhost:3000/restaurants/4
只有这样restoDetails 函数才会完成它的日志。
注意,在app的init函数中,我也是这样做的
if (window.history && window.history.pushState) {
Backbone.history.start({pushState: true});
您能否解释一下# 发生了什么,以至于当我单击链接时没有调用restoDetails 函数?
我还应该注意,如果我从这样的链接中删除 #
<a href="restaurants/{{= id }}"
那么这个问题就不存在了。但是,我得到代码的tutorial 使用了#,所以我认为这是必要的。
@muistooshort 的进一步评论,解决了我上面描述的问题
如果我没有像这样使用 pushstate
if (window.history ) {
Backbone.history.start();
}
然后我用#开始我的链接
<a href="#restaurants/{{= id }}"
当我点击那个链接时,路由器中的方法就会被触发
routes:{
"":"list",
"restaurants/:id":"restoDetails"
},
警报正在被调用
restoDetails:function (id) {
alert('in resto');
但是,如果我确实使用 pushstate
if (window.history && window.history.pushState) {
Backbone.history.start({pushState: true});
}
我设置了没有#的链接
<a href="restaurants/{{= id }}"
然后,如果我单击该链接,则不会调用应通过路由触发的函数中的警报。即这个警报现在没有发生。
restoDetails:function (id) {
alert('in resto');
为什么在启用 pushstate 时单击链接时不会触发此警报?
我还应该注意,如果我使用 pushstate,如果路由器没有触发该功能,它会回退到默认的 Rails 显示操作,因此渲染 json 的结果:@restaurants,root:false出现在 /restaurants/1 页面上
【问题讨论】:
-
您打算使用 History API 吗? diveintohtml5.info/history.html
-
你在做什么和jsfiddle.net/ambiguous/CEpPA不一样?
-
@muistooshort 对我有用。就是这个没有(它也不能在小提琴中工作):即当我单击启用了 pushstate 的链接并且没有使用链接中的 # 时它没有记录 jsfiddle.net/mjmitche/CEpPA/1
-
@muistooshort 根据您在威尔回答下方的评论,我认为它也应该像我在小提琴中设置的那样工作
-
PushState 在 jsfiddle.net 上有点麻烦,不过它应该可以在现实生活中使用。
标签: backbone.js