Backbone.js PushState True [英] Backbone.js PushState True

查看:91
本文介绍了Backbone.js PushState True的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在主干网中创建了一个站点,出于各种原因,我决定要删除URL中的哈希.我已经更改了历史.从

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(); 

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

但是一旦我这样做,路由就会停止正常工作.

but once I do that the routing stops working correctly.

我的路由如下:

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: '/'
});

如果我在不使用pushState的情况下运行它,就可以正常工作;如果在我使用pushState的情况下运行,它就不能到达console.log("artists");部分,并且我不明白为什么,有人可以向我解释我在做什么错吗?/p>

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?

推荐答案

您需要阻止a元素执行其常规操作并让骨干路由器对其进行路由.

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

我将使用jQuery编写示例以概述应该发生的情况:

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

});

这篇关于Backbone.js PushState True的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆