Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
516 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...