BackboneJS - 路由器问题 - 如何获得干净的 URL [英] BackboneJS - Router issues - how to get clean URL's
问题描述
好的,我有
{{#each mainmenu}}
<li>
<a href="#pages/{{this.url}}"><h2>{{this.name}}</h2></a>
</li>
{{/each}}
在我的路由器中
routes: {
'': 'index',
'pages/firstpage' : 'firstpage',
'pages/secondpage' : 'secondpage',
'pages/thirdpage' : 'thirdpage'
},
initialize: function () {
Backbone.history.start({pushState: false});
}
我的json文件是:
{
"name":"First page",
"id":"1",
"url":"firstpage"
},
{
"name":"Second page",
"id":"2",
"url":"secondpage"
},
{
"name":"Third page",
"id":"3",
"url":"thirdpage"
}
现在的方式我的 URL 是#pages/secondpage"——我怎样才能让 URL 显示pages/secondpage"——我试过pushState:true"但没有用......然后在我的主菜单中.js 视图我添加了一个事件:
the way it is right now my URL is "#pages/secondpage" - how can i get the URL to display "pages/secondpage" - i tried "pushState:true" which didnt work... then in my mainmenu.js view I added an event:
events: {
'click a.second': 'secondpage'
},
secondpage: function() {
var secondpageRouter = new Backbone.Router();
var route = 'pages/secondpage';
secondpageRouter.navigate(route, {trigger: true});
}
但这也不起作用......当我从上面的锚点中删除#pages/"时,我几乎得到了我想要的URLpages/secondpage" - 但点击后它说找不到URL"链接.所以这是怎么回事???
but that didnt work either... when I remove the "#pages/" from the anchor above, I almost get the URL I want "pages/secondpage" - but it says "URL could not be found" after clicking the link. So what's going on here???
请帮助任何人?
推荐答案
了解必要时您需要能够从服务器提供这些 url,请阅读此处的文档:http://backbonejs.org/#History
Understand that you need to be able to serve these urls from the server if necessary, read the docs here: http://backbonejs.org/#History
那么你至少需要做三件事.
Then you need to do at least three things.
首先,在定义路由器后,调用 Backbone.history
并确保 pushState 为真:
First, after you have defined your routers, call Backbone.history
and make sure pushState is true:
Backbone.history.start({ pushState: true })
其次,去掉链接中的所有#
,像这样:
Second, get rid of all the #
in your links, like this:
<a href="pages/{{this.url}}"><h2>{{this.name}}</h2></a>
第三,这很重要,您需要拦截本地链接上的所有点击并阻止它们的默认行为,即将您路由到新页面.使用 jQuery 这很容易:
Third, and this is important, you need to intercept all clicks on local links and prevent their default behavior, which would be to route you to a new page. This is easy with jQuery:
$(document).on("click", "a[href^='/']", function(event){
event.preventDefault();
RouterNameGoesHere.navigate($(event.target).attr("href"), {trigger: true});
});
如果您不使用 jQuery,请收听视图中的链接点击事件处理事件处理程序中的 url.我修改了您的代码以添加 event
参数和 event.preventDefault()
:
If you aren't using jQuery, listen to link click events in your views deal with the url in your event handlers. I modified your code to add the event
argument and event.preventDefault()
:
events: {
'click a.second': 'secondpage'
},
secondpage: function(event) {
event.preventDefault();
var secondpageRouter = new Backbone.Router();
var route = 'pages/secondpage';
secondpageRouter.navigate(route, {trigger: true});
}
这篇关于BackboneJS - 路由器问题 - 如何获得干净的 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!