Arch
Arch

Reputation: 1419

Usual use of route params in Ember

In ember js, I was wondering what is the usual method of using the route params that is normally available in the model hook?

Sometimes I find I need access to one of the params inside the controller; let's say to make an ajax request due to an action or something. Now normally you return a model in the model hook that usually has the id in it too. But I have cases where I don't need to get a model, just need the value. I can return an object or the value as the "model" in this case but it seems kind of strange. Is there no way to just access the params directly in a controller instead of passing the value around? Can you access the current route data from the controller?

Another thing; I have a route that requires two dynamic segments. So I create a resource with a route. Now in my route, I need access to both of those params. Do I have to pass them through the model hook? And then in the sub controller I have to use "needs" to access the parent controller's content? It seems a little bit too much of a workaround and it makes things really messy and unclear

To add on to this... If I pass some data to a route through something like transitionToRoute it skips the model method on the route. But then at that point you no longer have access to the params for the route. Is it expected that you call the serialize method on the model that you have in the setupController to figure out your params?

Upvotes: 1

Views: 8110

Answers (1)

borisrorsvort
borisrorsvort

Reputation: 906

You have to use query params which are only activatable in the canary build at the moment.

The reference of the subject can be found here:

https://github.com/emberjs/ember.js/pull/3182

The the general way to do it is like that:

App.Router.map(function() {
  this.resource('posts', {queryParams: ['sort', 'direction']}, function() {
    this.resource('post', {path: "/:id", queryParams: ['showDetails']});
  });
});

App.IndexRoute = Ember.Route.extend({
    beforeModel:      function( transition, queryParams ) {},
    model:            function( params, transition, queryParams ) {},
    afterModel:       function( resolvedModel, transition, queryParams ) {},
    setupController:  function( controller, context, queryParams ) {},
    renderTemplate:   function( controller, context, queryParams ) {}
});

/// transitionTo now will accept a final argument, which must be an object with the key queryParams.

this.transitionTo('post', object, {queryParams: {showDetails: true}});
this.transitionTo('posts', {queryParams: {sort: 'title'}});
this.transitionTo({queryParams: {direction: 'asc'}});

/// You can also use add query params to URL transitions as you would expect:

this.transitionTo("/posts/1?sort=date&showDetails=true");

Upvotes: 1

Related Questions