Ember可以处理到单个资源的多条路由吗?

时间:2013-10-09 11:03:26

标签: ember.js

我想通过usernameuser_id在我的网络应用中显示个人资料页面。我试过以下但没有成功,有什么想法吗?

MyApplication.Router.map(function () {

    this.resource('user', { path: '/user' }, function () {
        this.resource('profile', {path: '/profile/id/:user_id'});
        this.resource('profile', {path: '/profile/:user_username'});
    });

    this.resource('notFound', {path: '/notfound'});
});

4 个答案:

答案 0 :(得分:2)

您可以将这两个资源合并为一个,如下所示:

MyApplication.Router.map(function () {
  this.resource('user', { path: '/user' }, function () {
    this.resource('profile', {path: '/profile/id/:value'});
  });
});

MyApplication.ProfileRoute = Ember.Route.extend({
  model: function(params) {
    var value = params.value;
    if (isNaN(value)) {
      return this.store.find('user', { username: value });
    } else {
      return this.store.find('user', value);
    }
  }
});

如果网址中的value是一个数字,它会执行findById;否则它将执行findQuery。显然,如果某个用户名是一个数字,这种方法将失败。

答案 1 :(得分:2)

似乎Ember不应该以这种方式使用。我已阅读551上的问题571Embers Github。我认为最好坚持用id显示用户,以避免违反框架。

答案 2 :(得分:0)

如果URL是您的重要部分,您可以更改资源名称并保持网址前缀相同,例如:

MyApplication.Router.map(function () {
  this.resource('user', { path: '/user' }, function () {
    this.resource('profileByUserId', {path: '/profile/id/:user_id'});
    this.resource('profileByUsername', {path: '/profile/:user_username'});
  });
  this.resource('notFound', {path: '/notfound'});
});

希望它有所帮助。

答案 3 :(得分:0)

可以使用配置文件资源的嵌套路由

MyApplication.Router.map(function () {

    this.resource('user', { path: '/user' }, function () {
        this.resource('profile', function(){
            this.route('byid',{path: '/id/:user_id'});
            this.route('byname',{path: '/name/:user_username'});
        });
    });

    this.resource('notFound', {path: '/notfound'});
});

但请记住使用user_name实现序列化以定义路由 http://emberjs.com/guides/routing/defining-your-routes/

previos aproach也是有效的恕我直言