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?
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 to navigate
unless they have a data-bypass
attribute:
$(document).on("click", "a:not([data-bypass])", function(evt) { var href = { prop: $(this).prop("href"), attr: $(this).attr("href") }; var root = location.protocol + "//" + location.host + Backbone.history.options.root; if (href.prop && href.prop.slice(0, root.length) === root) { evt.preventDefault(); Backbone.history.navigate(href.attr, true); } });
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.
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:
$(document).on('click', 'a[href^="/"]', function (event) { // here, ensure that it was a left-mouse-button click. middle click should be // allowed to pass through event.preventDefault(); Backbone.history.navigate(this.href); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With