听起来您的问题不一定是如何隐藏模式,而是如何防止渲染/未更改的视图在路由到时重新渲染。
解决此问题的一种方法是维护“currentView”,并在路由处理程序中测试该视图以查看是否需要为路由完成工作。
也可以专门为模态视图保留一个类似的变量,它总是在路线上首先关闭。
// In some scope accessible to the router
var currentView, modalView; // or app.currentView, etc.
// extend your router's `navigate` to always close the modal
navigate: function (fragment, options) {
modalView && modalView.close(); // or however you close your modal
Backbone.history.navigate(fragment, options);
return this;
}
// in your modal route(s)
//
// Disclaimer here: if your modal windows are part of the history,
// their routes should probably also indicate what should be
// rendered *under* the modal, e.g. `/someroute/modal`, etc.
// Otherwise, what happens if a browser steps "back" into a modal
// route via history, or a direct link? You probably want something
// to render under the modal.
modal: function () {
modalView = new ModalView(); // or change the modal's content, etc
// given the above point, you may want to render the view under this
// modal here:
this.index(); // for example
// then continue to show your modal
},
// then in your other routes, for example `index`:
index: function () {
// test somehow to make sure that the view needs to be rendered
if (currentView instanceof IndexView) return;
currentView = new IndexView();
// continue to render/show the currentView
}