cjroebuck
cjroebuck

Reputation: 2263

Ember - How to set a variable when in admin route

I want to set some state variable which can be used to add a css class to my header template only when I am in the admin section of my app (i.e. any url beginning with /admin). I have the following routes:

this.resource('admin', { path: '/admin' }, function() {
    this.route('dashboard', { path: '/' });
    // more admin routes...
}
this.route('user')
// more routes...

Here is the setupController in my ApplicationRoute:

App.ApplicationRoute = App.Route.extend({
    setupController: function(){
        this.controllerFor('header').set('isInAdmin', false);
    }
}

And the same in AdminRoute:

App.AdminRoute = App.Route.extend({
  setupController: function(){
    this.controllerFor('header').set('isInAdmin', true);
  }
});

This works fine but once I have navigated into an admin route, and navigate back to a non-admin route, I'm not sure how to reset the isInAdmin variable.

Upvotes: 1

Views: 1438

Answers (2)

cjroebuck
cjroebuck

Reputation: 2263

I just read about the deactivate hook on Ember.Route:

http://emberjs.com/api/classes/Ember.Route.html#method_deactivate

This hook is executed when the router completely exits this route. It is not executed when the model for the route changes.

So I added:

App.AdminRoute = App.Route.extend({
  deactivate: function(){
    this.controllerFor('header').set('isInAdmin', false);
  }
});

which also works, however Márcio's answer is probably a little neater

Upvotes: 0

Marcio Junior
Marcio Junior

Reputation: 19128

The application controller have a computed property called currentPath. That property is equal the current path, for example, transitioning to admin/dashboard will return admin.dashboard in currentPath, going to /foo return foo etc.

So you can use the following code to know when a admin route is entered:

App.ApplicationController = Ember.Controller.extend({
    isInAdmin: function() {
        var currentPath = this.get('currentPath');
        // if the first hierarchy is admin, so is a admin route
        return currentPath.split('.')[0] === 'admin';        
    }.property('currentPath')
});

And in your application template isInAdmin will be avaliable:

<script type="text/x-handlebars" data-template-name="application">        
    ...
    <div {{bind-attr class=isInAdmin}}>
    ...
    </div>
    ...
</script>

Give a look in that fiddle to see this in action http://jsfiddle.net/marciojunior/j5PRe/

Upvotes: 4

Related Questions