我正在研究如何使用Ember.Router
处理应用程序中的无效路由。
当前,如果我输入一个无效的路径,例如myapp.com/#FooBarDoesntExist,它会重定向到索引路由('/')。我希望定义一个notFound或404状态,以便可以将其路由到,这样我就可以告知用户发生了什么。而不是他们被转到主页。
我正在研究如何使用Ember.Router
处理应用程序中的无效路由。
当前,如果我输入一个无效的路径,例如myapp.com/#FooBarDoesntExist,它会重定向到索引路由('/')。我希望定义一个notFound或404状态,以便可以将其路由到,这样我就可以告知用户发生了什么。而不是他们被转到主页。
处理这个问题的一个好方法是声明一个路由,将所有可能的网址映射到你的路由中。你可以在这里找到一个例子:http://jsfiddle.net/mbreton/r3C9c/
var App = Ember.Application.create();
App.Router.map(function(){
this.route('detail', {path: "detail"});
this.route('missing', { path: "/*path" });
});
App.MissingRoute = Em.Route.extend({
redirect: function () {
Em.debug('404 :: redirection to index');
this.transitionTo("index");
}
});
App.ApplicationView = Em.View.extend({
didInsertElement:function(){
$('#missingLink').on('click', function (e){
window.location.hash = "#/pepepepepep";
return false;
});
}
});
在这个例子中,所有未知的网址将被重定向到主页路由。Ember.Router在当前版本中不提供处理未知路由的方法。是时候动手解决了!
这里的想法是:我们有Ember.Router.route(path)
方法,该方法会使用请求的(可能未知的)路径进行调用。在调用此方法后,路由器的路径已知。因此,如果我们比较请求的路径和实际路径,并且它们不同 - 那么请求的路径无效,我们可以将用户重定向到404页面。
App.Router = Ember.Router.extend({
route: function(path) {
this._super(path);
var actualPath = this.get("currentState").absoluteRoute(this);
if (path !== actualPath) {
this.transitionTo("404page");
}
}
});
App.Router = Ember.Router.extend({
checkPath: function (path) {
path = path.replace(this.get('rootURL'), '').replace(/^(?=[^\/])/, "/");
var resolvedStates = this.get("states.root").resolvePath(this, path);
var lastState = resolvedStates.get("lastObject");
return lastState.match.remaining == "";
},
route: function(path) {
if (this.checkPath(path)) {
this._super(path);
} else {
this.transitionTo("404page");
}
}
});
这种解决方案也有缺点 - 它使用标记为私有的resolvePath
方法。尽管如此,我会使用这个解决方案,因为它比第一个更有效。
var
- iConnorRouter.map(function () {
this.route('home');
this.route('login');
this.route('404', { path: '/*path' }); // capture route in path
});
404.hbs
中。