问题
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