Backbone.js PushState True

拥有回忆 提交于 2019-11-28 05:43:02

问题


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?


回答1:


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

});



回答2:


Now I see why the need to globally override the tag behavior isn't in the documentation. I think we are intended to use handle navigation in our views like so:

MyView = Backbone.View.extend({
  events: {
    "click a.foo": "foo"
  },

  foo: function(e){
    e.preventDefault();
    history.navigate("foo");
    $("#output").append("foo");
  }
});

However if we want to retain the option to use simple HREFs in our tags we have to intercept the click behavior as in the above.

If you have a hybrid app, some links internal to backbone, and some forcing a page refresh, it's not right to preventDefault() for every link. Links to other parts of the app will be broken.

One can use a variation of the above and take advantage of the fact that if there is no internal view to navigate to, Backbone.history.navigate() will return false.

$(document).on("click", "a", function(e)
{

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

    var res = Backbone.history.navigate(href,true);
    //if we have an internal route don't call the server
    if(res)
        e.preventDefault();

});


来源:https://stackoverflow.com/questions/28323836/backbone-js-pushstate-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!