2

不知道如何强制主干正确导航到这样的路由:

页/#/频道/名称

代替

页面#频道/名称

或者

页面#/频道/名称

我的路由器使用一个主要模型并观察其状态,因此在这种情况下,路由器应该能够在不触发其事件的情况下更改 URL。

我试着这样做:

router.navigate("#/channel/" + encodeURIComponent(appState.data.channelName), { trigger: false });

但在这种情况下,“触发器:假”不起作用,所以我收到了不受欢迎的路由器事件调用。

Backbone.history 根设置为“/”,我目前没有使用 pushState。

请参见下面的代码示例:

var Router = Backbone.Router.extend({
    routes: {
        "": "index",            
        "index": "index",
        "channel/:channelName": "changeChannel"
    },

    initialize: function (options) {
        var router = this;

        if (options.model) {
            router.model = options.model;
        } else {
            //TODO: throw error
            return;
        }

        //update url in cases of model channelSelection changes
        router.model.on("stateChangeAccepted", function (appState) {
            switch (appState.mode) {
                case "channel":
                    router.navigate("/channel/" 
                        + encodeURIComponent(appState.data.channelName), { trigger: false });
                    break;                    
            }
        });
    },

    index: function () {
        var router = this;

        router.model.trigger("stateChangeRequest", {
            mode: "channel",
            data: {
                channelIndex: 0
            }
        });

    },

    changeChannel: function (channelName) {
        var router = this;

        router.model.trigger("stateChangeRequest", {
            mode: "channel",
            data: {
                channelName: decodeURIComponent(channelName)
            }
        });

    }
});
4

1 回答 1

0

您的router.navigate呼叫与您定义的路线不匹配:

routes: {
  "": "index",            
  "index": "index",
  "channel/:channelName": "changeChannel"
},

这意味着频道的 URL 应该是http://host.com/#channel/someChannel. 但是,您的 router.navigate 调用是router.navigate('#/channel...)router.navigate('/channel...)。它应该是:

router.navigate("channel/" + encodeURIComponent(appState.data.channelName), { trigger: false });

但是,如果您想使用类似 的路线http://host.com/#/channel/someChannel,那么您的路线应该是:

routes: {
  "": "index",            
  "index": "index",
  "/channel/:channelName": "changeChannel"
},

你的导航电话应该是:

router.navigate("/channel/" + encodeURIComponent(appState.data.channelName), { trigger: false });
于 2012-06-25T13:07:59.417 回答