简体   繁体   中英

Ember.js router and dynamic segments

I have been using Ember's Router (v1.0.pre) with single dynamic segments and really happy with it.
So much magic .

However, I'm struggeling with multiple dynamic segments:

  • What should serialize() / deserialize() return?
  • How should the transitionTo() call and the contex there look like?

Can somebody shed some light onto this?

  • serialize and deserialize should only be implemented when your context object has custom serialization (ie is not an ember-data model instance) . So you should not have to implement these methods while using the full ember stack.

  • transitionTo should be called from routes event handlers, and the context is passed as follow:

showPost: function (router, event) {
  var post = event.context;
  router.transitionTo('posts.show', post);
}

Given the showPost event has been trigged by action helper like that:

{{#each post in controller}}
  <a {{action showPost post}}>Show post {{post.title}}</a>
{{/each}}

More complex transitions can be achieved passing several context objects (for deeply nested routes):

router.transitionTo('posts.member.comments.show', post, comment);

post & comment contexts will be passed to appropriated routes while routing will descend into nested routes.


EDIT

Without ember-data, it would look like:

posts: Ember.Route.extend({
  route: 'posts',

  member: Ember.Route.extend({
    route: '/:post_id',

    show: Ember.Route.extend({
      route: '/'
    }),

    comments: Ember.Route.extend({
      route: 'comments',

      show: Ember.Route.extend({
        route: '/:comment_id'
      })
    })
  })
})

And you would have two classes App.Post & App.Comment , with find class methods, and id instances property.

App.Post = Ember.Object.extend({
  id: null
});
App.Post.reopenClass({
  find: function (id) {
    // retrieve data, instanciate & return a new Post
  }
});

App.Comment = Ember.Object.extend({
  id: null
});
App.Comment.reopenClass({
  find: function (id) {
    // retrieve data, instanciate & return a new Comment
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM