Backbone.history.navigate doesn't save parameters

青春壹個敷衍的年華 提交于 2019-12-11 04:22:57

问题


I have some routes:

routes: {
    "": "main",
    "!/": "main",
    "!/page": "page",
    "!/page/:id": "page"
},

Then I have some html link, for example:

<a href="site.com/#!/page/3">my link</a>

If i press to my link I access to url site.com/#!/page/3 and it's ok for me. But if I have this link:

<a href="javascript:void(0);" onclick="Backbone.history.navigate('!/page/3', {trigger:true});">my link</a>

I access to url site.com/#!/page/ (without id=3). Id is still defined. But after page reloading, I have a problem with my ID, because I have url: site.com/#!/page, and ID is not defined.

How can I navigate in Backbone with the following link tag?

<a href="javascript:void(0);" onclick="Backbone.history.navigate('!/page/3', {trigger:true});">my link</a>

回答1:


Backbone routing uses fragment just like any other anchor links would. You just need to use the href as it's suppose to be used:

<a href="#!/page/3">my link</a>

When clicking a link like this one, there's no need to set trigger to true as it's the default behavior. Backbone listens for hashchange or popstate events and triggers the route when necessary.


Also, the routes hash could be simplified:

routes: {
    "*anything": "main",
    "!/page(/:id)": "page"
},

See the routes documentation.

Routes can contain parameter parts, :param, which match a single URL component between slashes; and splat parts *splat, which can match any number of URL components. Part of a route can be made optional by surrounding it in parentheses (/:optional).



来源:https://stackoverflow.com/questions/39350737/backbone-history-navigate-doesnt-save-parameters

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