I have a backbone router with two routes registered like this
routes:{
"":"list",
"restaurants/:id":"restoDetails"
},
At the root of the application, when I'm listing the restaurants, I create links for each member of the list
<script id="restaurantListView" type="text/underscore">
<a href="#restaurants/{{= id }}" class="thumbnail plain">
<h5>{{= name }}</h5>
</a>
</script>
When I click on the link, it creates a link like this in the url bar
http://localhost:3000/#restaurants/4
However, there is no indication of the restoDetails
function getting called, contrary to what you'd expect from the route registered in the router. For example, this is not logging:
restoDetails:function (id) {
console.log('resto');
}
However, if I refresh the page with the url like this http://localhost:3000/#restaurants/4
, it changes to the same thing but without the hash
http://localhost:3000/restaurants/4
and only then does the restoDetails
function completes its log.
Note, in the init function of the app, I also do this
if (window.history && window.history.pushState) {
Backbone.history.start({pushState: true});
Can you explain what's happening with the #
such that the restoDetails function is not getting called when I click the link?
I should also note that if I remove the #
from the link like this
<a href="restaurants/{{= id }}"
then this problem doesn't exist. however, the tutorial I got the code from uses the #
so I assumed it was necessary.
Further to the comment by @muistooshort, which addresses the problem I've described above
If I'm not using pushstate like this
if (window.history ) {
Backbone.history.start();
}
Then I'm starting my links with the #
<a href="#restaurants/{{= id }}"
and when I click on that link, then the method in the router is getting trigger
routes:{
"":"list",
"restaurants/:id":"restoDetails"
},
and the alert is getting called
restoDetails:function (id) {
alert('in resto');
However, if I do use pushstate
if (window.history && window.history.pushState) {
Backbone.history.start({pushState: true});
}
and I set up the link without the #
<a href="restaurants/{{= id }}"
then if I click that link the alert in the function that should be triggered via the route is not getting called. ie this alert is not happening now.
restoDetails:function (id) {
alert('in resto');
why isn't this alert getting triggered if I click on the link when pushstate is enabled?
I should also note that, when the function isn't getting triggered by the router if I'm using pushstate, it's falling back to the default Rails show action, so the result of render json: @restaurants, root: false is appearing on the page /restaurants/1