Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone Router navigate and anchor href

Tags:

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?

like image 907
Evil Nodoer Avatar asked Aug 22 '12 21:08

Evil Nodoer


2 Answers

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.

like image 136
Chris Salzberg Avatar answered Sep 28 '22 00:09

Chris Salzberg


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); }); 
like image 45
nickf Avatar answered Sep 27 '22 23:09

nickf