Multiple dynamic segments in ember.js

前端 未结 2 1531
挽巷
挽巷 2021-01-14 01:50

I currently have my routes defined like this:

App.Router.map(function() {
    this.resource(\'players\', { path: \':page_id\' }, function() {
        this.re         


        
2条回答
  •  误落风尘
    2021-01-14 01:55

    While Sherwin's answer gave me a good idea of where I was going, I just wanted to put a complete example and give a general idea of what I ended up implementing. This could be of help for future reference.

    I'm going to make it simple by having the models be a simple int, that way we have a direct translation from url to model and vice versa.

    Templates:

    
    
    
    
    
    

    Application:

    App = Ember.Application.create();
    
    App.Router.map(function() {
      // This route has 2 dynamic segments
      this.resource("ab", { path: "/:a/:b" });
    });
    
    App.IndexRoute = Ember.Route.extend({
      redirect: function() {
        // At the entry point, encapsulate the 2 models in the context object,
        // and transition to the route with dual dynamic segments
        this.transitionTo('ab', {a: 3, b:4});
      }
    });
    
    App.AbRoute = Ember.Route.extend({
      model: function(params) {
        // The model is {a, b} directly
        return params;
      },
    
      renderTemplate: function(){
        // Render in the named outlet using the right controller
        this.render('a', {into: 'application', outlet: 'a', controller: 'a'});
        this.render('b', {into: 'application', outlet: 'b', controller: 'b'});
      },
    
      serialize: function(model) {
        return {
          a: model.a,
          b: model.b
        };
      },
    
      setupController: function(controller, model) {
        // Setup each controller with its own model
        this.controllerFor('a').set('model', model.a);
        this.controllerFor('b').set('model', model.b);
      }
    });
    

    Additional note:

    It would've been possible to have a single 'ab' template rendering {{model.a}} and {{model.b}} from the AbController, but I thought having separate controllers and templates was cleaner, and that it enabled reusability. Additionally, one of the controllers could've been an ArrayController and it would've work perfectly fine.

    JS Bin of the example

提交回复
热议问题