问题
ok I have
{{#each mainmenu}}
<li>
<a href="#pages/{{this.url}}"><h2>{{this.name}}</h2></a>
</li>
{{/each}}
and in my router
routes: {
'': 'index',
'pages/firstpage' : 'firstpage',
'pages/secondpage' : 'secondpage',
'pages/thirdpage' : 'thirdpage'
},
initialize: function () {
Backbone.history.start({pushState: false});
}
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"
}
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});
}
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???
Please help anyone?
回答1:
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.
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>
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});
});
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});
}
Here is an interesting blog post about this issue
来源:https://stackoverflow.com/questions/20504045/backbonejs-router-issues-how-to-get-clean-urls