为什么我的骨干路由器重定向到应用程序根目录?

时间:2012-09-07 20:00:18

标签: jquery-mobile backbone.js backbone-routing

我在我的应用中使用以下路由器:

app.Router = Backbone.Router.extend({
    // define the route and function maps for this router
    routes : {
        "" : "showLogin",
        // Sample usage: http://ServerManager/
        "login" : "login",
        // Sample usage: http://ServerManager/#login
        "logout" : "logout",
        // Sample usage: http://ServerManager/#logout
        "folders" : "listFolders",
        // Sample usage: http://ServerManager/#folders
        "folders/:name" : "showFolder",
        // Sample usage: http://ServerManager/#folders/System
        "*other" : "defaultRoute"
        // Sample usage: http://ServerManager/#badHash
    },
    showLogin : function() {
        console.log("Home page loaded. Redirecting to #login page.");
        this.navigate("login", {trigger: true, replace: true});
    },
    login : function() {
        //console.log("login route fired");
        // delete sessionStorage items and load a new loginview
        this.changePage(new app.LoginView()); 
    },
    logout : function() {
        //console.log("logout route fired");
        // Clear the token and other session items from sessionStorage
        sessionStorage.clear();
        this.navigate("login", {trigger: true, replace: true});
    },
    listFolders : function() {
        //console.log("listFolders route fired.")
        if (app.folderView === undefined) {
            console.log("creating new app.folderView");
            app.folderView = new app.FolderView();
        }
        else {
            console.log("using existing app.folderView");
        }
        this.changePage(app.folderView);
    },
    showFolder : function(name) {
        console.log( app.router.routes[Backbone.history.fragment] );
        //console.log("showFolder route fired.")
        this.changePage(new app.ServiceView({folder : name}));
        console.log( app.router.routes[Backbone.history.fragment] );
        //app.router.navigate("folder/" + name, {trigger: false});
    },
    defaultRoute : function() {
        alert("Error. Page doesn\'t exist.");
    },
    changePage : function(page) {
        $(page.el).attr("data-role", "page");
        page.render();
        $("body").append($(page.el));
        var transition = $.mobile.defaultPageTransition;
        $.mobile.changePage($(page.el), {changeHash : true, transition : transition});
    }
});

如果我使用

app.router.navigate("folders", {trigger: true, replace: true});

它成功将应用程序发送到服务器/#文件夹,但是当我通过

app.router.navigate("folders/" + id, {trigger: true, replace: true});

它会触发应用程序的根目录并加载我的登录页面。在重定向发生之前,我可以看到正确的URL(例如server / folders / folder1)暂时闪烁。关于这里发生了什么的任何想法?

1 个答案:

答案 0 :(得分:1)

Backbone路由器期待更多通用路由。

设置folders/:id路线,然后设置folders路线。

<强>更新

实际上,在考虑之后,情况可能并非如此。你可以发布控制台输出吗?它是否正在调用正确的函数?

也许$.mobile ... changeHash: true存在冲突。您可能只应该让其中一个框架为您更改url哈希。