Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set an Ember controller property

Tags:

ember.js

The application template to an Ember app I'm looking at uses a conditional check to determine which links to display

{{#if isAuthenticated}}
    link
{{else}}
    link...
{{/if}}

The isAuthenticated property is set conditionally based on whether the user is registered/logged in

App.AuthController = Ember.ObjectController.extend({
    currentUser: null,
    isAuthenticated: Em.computed.notEmpty("currentUser.email"),
    login: function(route) {
      var me;
      me = this;
      return $.ajax({
        url: "/users/sign_in.json",
        type: "POST",
        data: {
          "user[email]": route.currentModel.email,
          "user[password]": route.currentModel.password
        },
        success: function(data) {

          me.set('currentUser', data.user);

         return route.transitionTo('user', data.user);

The app is able to process registration and login without a problem, however, the application template is always showing the links for when a user is not authenticated. Is there some reason why isAuthenticated wouldn't be getting updated upon login based on the code you see here?

like image 461
BrainLikeADullPencil Avatar asked Sep 23 '13 15:09

BrainLikeADullPencil


1 Answers

If @mavilein and @chopper allow me to post a definitive answer to get this question fully covered, then here it goes:

ApplicationController

Since your ApplicationController is the one backing up your application template, you should requiere the AuthController using the needs API like this:

App.ApplicationController = Ember.ObjectController.extend({
  needs: ['auth']
  ...
});

Application template

Then you can access all of your AuthController's properties prefixing the access with controllers.auth, therefore in your application template you can then do:

{{#if controllers.auth.isAuthenticated}}
  link
{{else}}
  link...
{{/if}}

If you where to don't like the long name, there is also a shortcut for it:

 App.ApplicationController = Ember.ObjectController.extend({
  needs: ['auth'],
  isAuthenticated: Ember.computed.alias('controllers.auth.isAuthenticated')
  ...
});

Doing this, you can then in your application template simply do:

{{#if isAuthenticated}}
  link
{{else}}
  link...
{{/if}}

which in this case refers to the ApplicationController isAuthenticated property which in turn is computed from the originating controller AuthController.

Hope it helps.

like image 144
intuitivepixel Avatar answered Sep 21 '22 17:09

intuitivepixel