不知道如何强制主干正确导航到这样的路线:
页/#/信道/名称
而不是
page#channel / name
或
页#/信道/名称
我的路由器使用一个主模型并观察其状态,因此路由器应该能够在不触发其事件的情况下更改URL。
我试着这样做:
router.navigate("#/channel/" + encodeURIComponent(appState.data.channelName), { trigger: false });
但是在这种情况下“trigger:false”不起作用,所以我得到了一个不受欢迎的路由器事件调用。
Backbone.history root设置为“/”,我目前没有使用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)
}
});
}
});
答案 0 :(得分:0)
您的router.navigate
来电与您定义的路线不符:
routes: {
"": "index",
"index": "index",
"channel/:channelName": "changeChannel"
},
这意味着频道的网址应为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 });