我有一个编辑器视图,如果有未保存的更改,我会提示窗口关闭以及主干路径。
问题是Backbone.Router.execute在网址更改后运行,因此我尝试实施最可靠,最优雅的方法来阻止网址更改。
在下面的示例中,单击“关于”路由将阻止路由回调,然后回滚网址更改 - 我似乎不太理想,我必须使用[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
(因为它创建了一个历史记录条目)。 / p>
你能想到一个更好的方法吗?我知道jQuery on-click可以在url更改之前捕获事件,但我不确定如何将其与window.history.back()
很好地集成。感谢。
Backbone.Router
var HomeView = Backbone.View.extend({
template: '<h1>Home</h1>',
initialize: function () {
this.render();
},
render: function () {
this.$el.html(this.template);
}
});
var AboutView = Backbone.View.extend({
template: '<h1>About</h1>',
initialize: function () {
this.render();
},
render: function () {
this.$el.html(this.template);
}
});
var ContactView = Backbone.View.extend({
template: '<h1>Contact</h1>',
initialize: function () {
this.render();
},
render: function () {
this.$el.html(this.template);
}
});
var AppRouter = Backbone.Router.extend({
routes: {
'': 'homeRoute',
'home': 'homeRoute',
'about': 'aboutRoute',
'contact': 'contactRoute'
},
execute: function(callback, args, name) {
if (window.location.hash === '#/about') {
window.history.back();
return false;
}
if (callback) {
callback.apply(this, args);
}
},
homeRoute: function () {
var homeView = new HomeView();
$("#content").html(homeView.el);
},
aboutRoute: function () {
var aboutView = new AboutView();
$("#content").html(aboutView.el);
},
contactRoute: function () {
var contactView = new ContactView();
$("#content").html(contactView.el);
}
});
var appRouter = new AppRouter();
Backbone.history.start();
我唯一能想到的就是用jQuery监听点击和处理事情,或保存最后一个哈希并执行<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="http://underscorejs.org/underscore.js"></script>
<script src="http://backbonejs.org/backbone.js"></script>
<div id="navigation">
<a href="#/home">Home</a>
<a href="#/about">About</a>
<a href="#/contact">Contact</a>
</div>
<div id="content"></div>
。