Multiple Dynamic Segments in a Single Resource in Ember.js

浪子不回头ぞ 提交于 2019-12-04 01:22:25

问题


Is there a way to have multiple dynamic segments with a single resource? My use case is to avoid letting the user hit index routes.

Example:

this.resource('tracks', { path: 'albums/:album_id/tracks/:tracks_id' });

And I'd like to avoid the user from hitting the following routes:

albums/:album_id
albums/:album_id/tracks
albums/:album_id/tracks/:track_id

Routes:

this.resource('albums', { path: 'albums' }, function(){
  this.resource('album', { path: '/:album_id' }, function() {
    this.resource('tracks', { path: 'tracks' }, function(){
      this.resource('track', { path: '/:track_id' });
    });
  });
});

Any help would be greatly appreciated.

Defining Your Routes

NOTE: If you define a resource using this.resource and do not supply a function, then the implicit resource.index route is not created.


回答1:


It would be better to use Ember's nested routes. Each route having its own dynamic segment.

App.Router.map(function () {
    this.resource('albums', { path: '/albums' }, function () {
        this.resource('album', { path: ':album_id' }, function () {
            this.resource('tracks', { path: 'tracks' }, function () {
                this.resource('track', { path: ':track_id' });
            });
        });
    });
});

If you want to show the user the first track immediately after clicking an album, you could use a redirect.

App.AlbumRoute = Ember.Route.extend({
    afterModel: function (album, transition) {
        this.transitionTo('track', {album_id: album.id, track_id: album.tracks[0].id});
    },
});

Check out the docs on redirection: http://emberjs.com/guides/routing/redirection/




回答2:


Just for completeness sake, the index routes aren't necessary, they are just a freebie convenience if you define them, if you don't define them it won't go to them.

http://emberjs.jsbin.com/eMofowUQ/1/edit

And you can define multiple slugs in a single path and go directly to it, just note you'll only have a single model for that single resource, so you'll have to deal with that.

http://emberjs.jsbin.com/eMofowUQ/2/edit




回答3:


A possible solution for us was to use the following:

App.AlbumsIndexRoute = Ember.Route.extend({ 
    redirect: function(){ 
        this.transitionTo('dashboard');
    } 
});    


来源:https://stackoverflow.com/questions/20410838/multiple-dynamic-segments-in-a-single-resource-in-ember-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!