14

我试图弄清楚如何使用Ember.Router.

目前,如果我输入无效路由,例如 myapp.com/#FooBarDoesntExist,它将重定向到索引路由 ('/')。如果我可以定义它会路由到的 notFound 或 404 状态,我会喜欢它,这样我就可以通知用户发生了什么。与他们被丢弃在主页相反。

4

3 回答 3

19

处理此问题的一个好方法是声明一个路由,该路由映射除您的路由之外的所有可能的 url。你可以在这里举个例子: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;      
        });
    }
});

在这个例子中,所有未知的 url 都被重定向到索引路由。

于 2013-07-11T12:49:26.663 回答
6

当前版本的 Ember.Router 不提供处理未知路由的方法。是时候破解了!

解决方案 1 - 快速而肮脏

这里的想法如下。我们有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");
      }
    }
  });

这种解决方案非常昂贵。例如,如果当前状态是“/a/b/c”,并且用户想要导航到“/b/d/e/unknown”,路由器将尽职尽责地进入已知状态“b”、“d”和“e”,然后我们才将路径视为未知。如果我们能在实际路由开始之前告诉它,那就太好了。

解决方案 2 - 摆弄私有方法

在这里,我们检查给定路径的有效性,然后才告诉路由器继续:

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标记为私有的方法。尽管如此,我还是会使用这个解决方案,因为它比第一个更有效。

于 2012-10-12T19:06:26.267 回答
2

在 Ember 1.13 中推荐的方法是创建一个包罗万象的路由:

Router.map(function () {
  this.route('home');
  this.route('login');
  this.route('404', { path: '/*path' });  // capture route in path
});

然后将您的 404 模板放入404.hbs.

于 2015-08-26T22:15:33.697 回答