Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js PushState True

I've created a site in backbone and for various reasons I've decided I want to remove the hash in the URL. I've changed history.start from

Backbone.history.start(); 

to

Backbone.history.start({pushState: true, root: '/'});

but once I do that the routing stops working correctly.

My routing looks like this:

var Router = Backbone.Router.extend({
  routes: {
    "": "home",
    "home": "home",
    "artists": "artists",
  }
});

var router = new Router;
router.on('route:home', function() {
  console.log("home");
  // Code
});

router.on('route:artists', function() {
  console.log("artists");
  // Code
});

//Backbone.history.start();
Backbone.history.start({
  pushState: true,
  root: '/'
});

if I run it without pushState it works fine, if I run it with pushState it doesn't reach the console.log("artists"); part and I don't understand why, could someone explain to me what I'm doing wrong?

like image 961
mrdookles Avatar asked Oct 23 '25 20:10

mrdookles


1 Answers

You need to prevent a element to carry on its regular action and have backbone router route it.

I'll write the example using jQuery to outline what should happen:

$(document).on("click", "a", function(e)
{
    e.preventDefault(); // This is important

    var href = $(e.currentTarget).attr('href');

    router.navigate(href, true); // <- this part will pass the path to your router

});
like image 83
Mjh Avatar answered Oct 25 '25 12:10

Mjh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!