BackboneJS - Router issues - how to get clean URL's

廉价感情. 提交于 2019-12-12 07:24:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!