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文件是:
and my json file is:
{
"name":"First page",
"id":"1",
"url":"firstpage"
},
{
"name":"Second page",
"id":"2",
"url":"secondpage"
},
{
"name":"Third page",
"id":"3",
"url":"thirdpage"
}
这是现在我的网址是#网页称为/ secondpage的方式 - 我怎样才能获取URL,以显示网页称为/ secondpage - 我试图pushState的:真正的它没有工作......然后在我的MainMenu .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});
}
但没有工作要么...当我从锚卸下上面的#页/,我几乎得到了我想要网页称为/ 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 })
二,摆脱所有的#
在你的链接,如:
<a href="pages/{{this.url}}"><h2>{{this.name}}</h2></a>
三,这是非常重要的,你需要截取本地链接和prevent它们的默认行为,这将是路由你到一个新的页面的所有点击。这是很容易使用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链接点击事件。我修改code以添加了事件
参数和事件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屋!