In a backbone-enabled app, I have seen code that continues to use <a href="#foo"></a>
, while the anchor click is handled by a backbone event handler.
Alternatively, the navigation to #foo can be handled by:
Router.history.navigate("foo");
I believe the latter is the superior approach because it allows easy migration to and from HTML5's pushState functionality. And if we do use pushState, Backbone would be able to gracefully degrade to #foo for browsers that do not support pushState.
As I am still new to Backbone, can someone more experienced and knowledgable confirm that this is the case?
Chris' answer is awesome, but there's one addition to it that makes it even better.
Backbone.history.navigate()
actually returns true or false telling us if it could route to it internally. We can therefore skip thedata-bypass
attribute and do the following instead:I personally have
pushState
enabled and use the approach taken in Tim Branyen's backbone-boilerplate of adding a click handler that sends all link clicks tonavigate
unless they have adata-bypass
attribute:This works pretty well and as @nickf mentions has the advantage that you don't have to use the hash/hashbang hack, even for browsers that do not support pushState.
Yes I try to use as much Router.history.navigate as I can in my Backbone apps. This also has the benefit of if the user types in the URL "/foo" in their browser, Backbone routes it properly. Obviously if it is an external link or something you don't want to handle with Backbone then you should not include it.
You should write your links as their "proper" addresses, that is, not with the hash which is just a hack to get around some deficiencies of a particular browser. To then make it all work, attach a click handler to catch clicks on these items and pass the urls to Backbone.history, which can then use pushState or convert to a hashbang'd url if needed. For example: