使用Page.js和引导选项卡进行客户端路由

时间:2015-03-14 15:10:47

标签: jquery twitter-bootstrap

我试图让Page.js客户端路由库与Bootstrap 3 built in tabs一起使用,以便浏览器中的后退和前进按钮在路由之间导航并显示相应的选项卡。

使用我当前的代码设置它有时会工作,但它的行为不一致。有时导航到访问过的选项卡,有时它没有(没有任何反应)。我的选项卡是使用带有数据切换的Bootstrap选项卡构建的,因此它仅使用内置的Bootstrap javascript来实现它的默认行为。

如果有人能够帮助我在路线之间设置后退和前进按钮,同时显示相应的标签,我将不胜感激!

的Javascript

var page = page;

/**
 * Define routes and callbacks
 */
page('/profile', function(ctx) {
    showTab(ctx.pathname);
    console.log(ctx.pathname);

});

page('/search', function(ctx) {
   showTab(ctx);
    console.log(ctx.pathname)

});

page('/account',  function(ctx) {
    showTab(ctx.pathname);
    console.log(ctx.pathname);
});

/**
 * Visit route corresponding to the current clicked tab
 */

$(document).ready(function () {
    $(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
        console.log("Hello again")
        var targetView = $(e.target).attr('href')
        targetView = targetView.replace("#", "");
        page('/'+ targetView)
    })
});

/**
 * Show tab corresponding to current route/path
 */

function showTab(path) {
        path = path.toString().replace('/', '');
        var selector = '.nav-tabs a[href="#' + path + '"]'
        $(selector).tab("show");
}

//start route
page();

1 个答案:

答案 0 :(得分:1)

I got stuck in the exact same situation recently! Here's how I solved it.

The Problem

Assume you were on /account then navigated to /search and pressed back button, which leads you to /account. Following happens:

  1. Page.js receives url (which is /account) and calls its handler, for this case:

    page('/account',  function(ctx) {
        showTab(ctx.pathname);
        console.log(ctx.pathname);
    });
    
  2. in showTab following code gets executed:

    ...
    $(selector).tab("show");
    ...
    

    which shows the corresponding tab. So far so good...

  3. on('shown.bs.tab', ... event gets triggered and makes this happen:

    page('/'+ targetView)
    

    which effectively redirects you to the same page you're on already and makes your browser move one step forward so it removes all 'forward' history.

The Solution

... is very simple: just check if you are already on the desired url before calling page() once again in on('shown.bs.tab', ...), something like this:

if (window.location.pathname != '/' + targetView)
    page('/' + targetView)